使用scala将spark中的时间戳更改为UTC格式

change the timestamp to UTC format in spark using scala

这个问题有点类似于问题:Change the timestamp to UTC format in Pyspark

基本上,它使用 scala.[=14 将带有偏移量的时间戳字符串格式 ISO8601 转换为 UTC 时间戳字符串(2017-08-01T14:30:00+05:30 -> 2017-08-01T09:00:00+00:00) =]

我是 scala/java 的新手,我检查了 spark 库,他们在不知道时区的情况下无法转换,我不知道时区,除非(我以丑陋的方式解析它或使用 java/scala 库?)有人可以帮忙吗?

更新:更好的方法是:在 spark 中设置时区会话,然后使用 df.cast(DataTypes.TimestampType) 进行时区转换

您可以使用 java.time 原语来解析和转换您的时间戳。

scala> import java.time.{OffsetDateTime, ZoneOffset}
import java.time.{OffsetDateTime, ZoneOffset}

scala> val datetime = "2017-08-01T14:30:00+05:30"
datetime: String = 2017-08-01T14:30:00+05:30

scala> OffsetDateTime.parse(datetime).withOffsetSameInstant(ZoneOffset.UTC)
res44: java.time.OffsetDateTime = 2017-08-01T09:00Z

org.apache.spark.sql.functions.to_utc_timestamp:

def to_utc_timestamp(ts: Column, tz: String): Column

Given a timestamp like '2017-07-14 02:40:00.0', interprets it as a time in the given time zone, and renders that time as a timestamp in UTC. For example, 'GMT+1' would yield '2017-07-14 01:40:00.0'.