spark dataframe将字符串格式的毫秒时间戳列转换为人类可读的毫秒时间

eblbsuwk  于 2021-07-12  发布在  Spark
关注(0)|答案(1)|浏览(393)

我有一个sparkDataframe,在epoche之后有一个以毫秒为单位的timestamp列。列是一个字符串。我现在想将列转换为可读的人类时间,但保留毫秒。例如:
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 |
+------------------+------------------------+
0vvn1miw

0vvn1miw1#

使用获取毫秒之前的时间 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|
+------------------+-----------------------+

相关问题