首页 > 解决方案 > Scala Spark 将日期转换为特定格式

问题描述

我正在将一些 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

标签: scalaapache-sparkdate-formatting

解决方案


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|
// +---------------------------------------------------------------+

推荐阅读