Ern*_*vic 5 timezone scala apache-spark
我需要从Spark DataFrame将纪元/ unix时间戳列(例如1509102527 = GMT:2017年10月27日,星期五,11:08:47)转换为本地化的时间戳,以获取特定时区的本地时间。
是否有一个Spark SQL函数可以采用unix时间戳并返回本地化的java.sql.Timestamp?
我已经尝试过使用from_unixtime
function,但是它会根据运行代码的计算机的默认系统时区返回本地化的时间戳。到目前为止,我发现的唯一解决方案是将时间戳转换回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
}
Run Code Online (Sandbox Code Playgroud)