scala - 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
解决方案
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|
// +---------------------------------------------------------------+
推荐阅读
- mysql - 本月总和与之前的差异 [mysql]
- java - 如果该 URL 包含路径变量,是否有任何方法可以在 ServletRequest 中找出确切请求的 URL?
- php - 使用最后插入的 id 插入问题
- python - WebDriverWait 未能等待该 URL
- powershell - 设置 IIS 默认应用程序池队列长度 Powershell
- java - maven 以什么顺序运行复合命令给出的阶段?
- stata - 使用 outreg2 导出结果
- javascript - 网络工作者是否有某种加载事件?
- ios - 由于循环条件,无法发出预编译的标头
- reactjs - 兄弟路线在reactjs中不起作用