首页 > 解决方案 > 从时间戳获取精确的毫秒数 - Spark Scala

问题描述

我在数据框(scala)中有一个时间戳列,并希望从中获取毫秒。unix_timestamp 是秒,我不能做 unix_timestamp*1000 因为我正在寻找精确的毫秒转换

输入数据框

+---------+-----------------------+-----+-----------------------+
|OrderName|DateTime               |Count|timestamp              |
+---------+-----------------------+-----+-----------------------+
|a        |2020-07-11 23:58:45.538|1    |2020-07-11 23:58:45.538|
|a        |2020-07-12 00:00:07.307|2    |2020-07-12 00:00:07.307|
|a        |2020-07-12 00:01:08.817|3    |2020-07-12 00:01:08.817|
|a        |2020-07-12 00:02:15.675|1    |2020-07-12 00:02:15.675|
|a        |2020-07-12 00:05:48.277|1    |2020-07-12 00:05:48.277|
+---------+-----------------------+-----+-----------------------+

Second column is string and i used to to_timestamp($"DateTime") to get 4th column
Example 2020-07-11 23:58:45.538 -> 1594537125538

标签: scalaapache-spark

解决方案


您可以使用 UDF 获得此信息,该 UDF 将您的字符串读入瞬间,然后将其转换为 Epoch 毫秒:

import org.apache.spark.sql.functions._
import java.time._
import java.time.format.DateTimeFormatter

//...

spark.udf.register("to_epoch_millis", 
                   (s: String) => LocalDateTime.parse(s, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"))
                       .toInstant(ZoneOffset.UTC).toEpochMilli())

然后

df.selectExpr("to_epoch_millis(DateTime) as ts").show()
+-------------+
|           ts|
+-------------+
|1594511925538|
|1594512007307|
+-------------+

以上假设DateTime是 UTC 时间戳。


推荐阅读