【问题标题】:Apache Spark: Fixing the timestamp formatApache Spark:修复时间戳格式
【发布时间】:2026-01-08 07:35:01
【问题描述】:

我正在尝试读取 csv 文件并将其附加到表中。对于日期列,它会抛出 Timestamp format must be yyyy-mm-dd hh:mm:ss 异常。

我经历了几个解决方案,但没有一个对我有用。

我正在尝试使用udf,但它引发了异常:

Schema for type java.util.Date is not supported

这是我尝试过的:

val dateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss")
val toDate = udf[Date, String](dateFormat.parse(_))
val schema = StructType(Array(StructField("id", LongType, nullable=true), StructField("name", StringType, nullable=true), StructField("date_issued", TimestampType, nullable=true)))
var df = spark.read.schema(schema).csv("./data/test.csv")
var df2 = df.withColumn("date_issued", toDate(df("date_issued")))
df2.show()

df2.write.mode(SaveMode.Append).jdbc("jdbc:postgresql://localhost:5432/db", "card", connectionProperties)

【问题讨论】:

  • 尝试使用java.sql.date 而不是java.util.date
  • SimpleDateFormat 返回java.util.date
  • 更新了我的答案,请查收。

标签: scala apache-spark apache-spark-sql


【解决方案1】:

问题是,需要将util日期转换为sql日期。

试试下面的代码。

def convertToDate(dateTime: String): Date = {

    val formatter = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss")
    val utilDate = formatter.parse(dateTime)
    new java.sql.Date(utilDate.getTime)
  }

然后将此函数转换为UDF。

val toDate = udf(convertToDate(_: String))

【讨论】: