scala - 从时间戳获取精确的毫秒数 - 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
解决方案
您可以使用 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 时间戳。
推荐阅读
- sql - 错误:声明短语中的“附近的语法不正确”
- c# - 从 Blazor 应用程序中的 WEB API 返回数据
- macos - 没有 App Bundle 的 QT 命令行可执行二进制文件是否有 Macdeployqt?
- winapi - 为什么在 Windows SetupAPI 中 LogSeverity #defined 为 DWORD
- c# - 无法在 Blazor razor 页面(Blazor 服务器端)中注入 Controller、DbContext
- javascript - 在Javascript中覆盖名为params的函数?
- javascript - 如何在 handlebars.js 中使用一个模板,同时在其中使用多个对象?
- javascript - 如何将事件侦听器添加到 Web 组件模板元素
- math - 三次/五次线性插值
- r - 如何使用 tidymodels 在我的结果变量中设置哪个级别是“事件”?