我需要从 Spark DataFrame 将 epoch/unix 时间戳列(例如 1509102527 = GMT:星期五,2017 年 10 月 27 日 11:08:47)转换为本地化时间戳,以便获取特定时区的本地小时。
是否有 Spark SQL 函数可以获取 unix 时间戳并返回本地化的 java.sql.Timestamp?
我已经尝试使用from_unixtime
函数,但它返回基于代码运行的计算机的默认系统时区的本地化时间戳。到目前为止,我找到的唯一解决方案是将时间戳转换回 UTC,然后从 UTC 转换为目标时区。
这是一个与解决方法一起使用的单元测试,但应该有更好的方法来做到这一点。
test("timezone localization should not change effective unix timestamp") {
import org.apache.spark.sql.functions._
val df = Seq(1509102527)
.toDF("unix_timestamp")
.withColumn("machine_localised_timestamp", from_unixtime('unix_timestamp))
.withColumn("utc_timestamp", to_utc_timestamp('machine_localised_timestamp, TimeZone.getDefault().getID()))
.withColumn("local_time", from_utc_timestamp('utc_timestamp, "Europe/Amsterdam"))
.withColumn("local_hour", hour('local_time))
.withColumn("reverted_unix_timestamp", unix_timestamp('local_time))
df.show(false)
val row = df.collect()(0)
row(row.fieldIndex("unix_timestamp")) shouldBe 1509102527
row(row.fieldIndex("reverted_unix_timestamp")) shouldBe 1509102527
row(row.fieldIndex("local_hour")) shouldBe 13
}
None
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)