Scala Spark 将日期转换为特定格式

Scala Spark convert date to a specific format

我正在将一些 JSON 文件读取到数据框中,我想将其中的一个字段转换为特定格式,JSON 文件具有以下格式的 server_received_time作为字符串,我想将其转换为 yyyy-MM-dd:hh

"server_received_time":"2019-01-26T03:04:36Z"

但我绑的东西都回来了 null

   df.select("server_received_time")
.withColumn("tx_date", to_date($"server_received_time", "yyy-MM-dd:hh").cast("timestamp"))
.withColumn("tx_date2", to_timestamp($"server_received_time", "yyy-MM-dd:hh").cast("timestamp"))
.withColumn("tx_date3", to_date(unix_timestamp($"server_received_time", "yyyy-MM-dd:hh").cast("timestamp")))
.withColumn("tx_date4", to_utc_timestamp(to_timestamp(col("server_received_time"), "yyyy-MM-dd:hh"), "UTC"))
.withColumn("tx_date5", to_timestamp($"server_received_time","yyyy-MM-dd:hh"))

.show(10, false)

+--------------------+-------+--------+--------+--------+--------+
|server_received_time|tx_date|tx_date2|tx_date3|tx_date4|tx_date5|
+--------------------+-------+--------+--------+--------+--------+
|2019-02-18T16:02:20Z|null   |null    |null    |null    |null    |
|2019-02-18T16:02:20Z|null   |null    |null    |null    |null    |
|2019-02-18T16:02:20Z|null   |null    |null    |null    |null    |
|2019-02-18T16:02:20Z|null   |null    |null    |null    |null    |
|2019-02-18T16:02:20Z|null   |null    |null    |null    |null    |
|2019-02-18T16:02:20Z|null   |null    |null    |null    |null    |
|2019-02-18T16:02:20Z|null   |null    |null    |null    |null    |
|2019-02-18T16:02:20Z|null   |null    |null    |null    |null    |
|2019-02-18T16:02:20Z|null   |null    |null    |null    |null    |
|2019-02-18T16:02:20Z|null   |null    |null    |null    |null    |
+--------------------+-------+--------+--------+--------+--------+

我想要 server_received_time 这种格式 yyyy-MM-dd:hh

格式不同。这应该如下工作:

df.select(date_format(to_timestamp($"server_received_time", "yyyy-MM-dd'T'HH:mm:ss'Z'"), "yyyy-MM-dd:hh").as("custom_date"))

to_ 方法采用实际格式,而不是所需的输出格式。要格式化,您必须将数据转换回字符串

import org.apache.spark.sql.functions._

val df = Seq("2019-02-18T16:02:20Z").toDF("server_received_time")

df.select(date_format(to_timestamp($"server_received_time"), "yyy-MM-dd:hh")).show
// +---------------------------------------------------------------+
// |date_format(to_timestamp(`server_received_time`), yyy-MM-dd:hh)|
// +---------------------------------------------------------------+
// |                                                  2019-02-18:05|
// +---------------------------------------------------------------+