如何更改 Spark 中的日期格式?

How to change date format in Spark?

我有以下数据框:

+----------+-------------------+
| timestamp|            created|
+----------+-------------------+
|1519858893|2018-03-01 00:01:33|
|1519858950|2018-03-01 00:02:30|
|1519859900|2018-03-01 00:18:20|
|1519859900|2018-03-01 00:18:20|

如何正确创建时间戳?

我能够创建 timestamp 列,它是纪元时间戳,但日期不重合:

df.withColumn("timestamp",unix_timestamp($"created"))

例如1519858893指向2018-02-28.

试试下面的代码

df.withColumn("dateColumn", df("timestamp").cast(DateType))

只需使用 date_formatto_utc_timestamp 内置函数

import org.apache.spark.sql.functions._
df.withColumn("timestamp", to_utc_timestamp(date_format(col("created"), "yyy-MM-dd"), "Asia/Kathmandu"))

您可以在此处查看一种解决方案 要详细说明字符串中具有不同格式 timestamp/date 的数据框,您可以这样做 -

val df = spark.sparkContext.parallelize(Seq("2020-04-21 10:43:12.000Z", "20-04-2019 10:34:12", "11-30-2019 10:34:12", "2020-05-21 21:32:43", "20-04-2019", "2020-04-21")).toDF("ts")

def strToDate(col: Column): Column = {
    val formats: Seq[String] = Seq("dd-MM-yyyy HH:mm:SS", "yyyy-MM-dd HH:mm:SS", "dd-MM-yyyy", "yyyy-MM-dd")
    coalesce(formats.map(f => to_timestamp(col, f).cast(DateType)): _*)
  }

val formattedDF = df.withColumn("dt", strToDate(df.col("ts")))

formattedDF.show()
+--------------------+----------+
|                  ts|        dt|
+--------------------+----------+
|2020-04-21 10:43:...|2020-04-21|
| 20-04-2019 10:34:12|2019-04-20|
| 2020-05-21 21:32:43|2020-05-21|
|          20-04-2019|2019-04-20|
|          2020-04-21|2020-04-21|
+--------------------+----------+

注意:- 此代码假定数据不包含任何格式的列 -> MM-dd-yyyy、MM-dd-yyyy HH:mm:SS