首页 > 解决方案 > Spark DataFrame 将字符串格式的毫秒时间戳列转换为以毫秒为单位的人类可读时间

问题描述

自纪元以来,我有一个带有时间戳列的Spark DataFrame ,以毫秒为单位。该是一个字符串。我现在想将该列转换为可读的人类时间,但保留毫秒。 例如:

1614088453671 -> 23-2-2021 13:54:13.671

我发现的每个示例都将时间戳转换为正常的人类可读时间,无需毫秒。

我有的:

+------------------+
|epoch_time_seconds|
+------------------+
|1614088453671     |
+------------------+

我想达到什么:

+------------------+------------------------+
|epoch_time_seconds|human_date              |
+------------------+------------------------+
|1614088453671     |23-02-2021 13:54:13.671 |
+------------------+------------------------+

标签: scalaapache-sparkapache-spark-sql

解决方案


可以使用 获得毫秒之前的时间date_format from_unixtime,而可以使用模获得毫秒。使用format_string.

val df2 = df.withColumn(
    "human_date",
    format_string(
        "%s.%s",
        date_format(
            from_unixtime(col("epoch_time_seconds")/1000),
            "dd-MM-yyyy HH:mm:ss"
        ),
        col("epoch_time_seconds") % 1000
    )
)

df2.show(false)
+------------------+-----------------------+
|epoch_time_seconds|human_date             |
+------------------+-----------------------+
|1614088453671     |23-02-2021 13:54:13.671|
+------------------+-----------------------+

推荐阅读