简体   繁体   English

使用Scala将时间戳更改为Spark中的UTC格式

[英]change the timestamp to UTC format in spark using scala

The question is kind of similar with the problem: Change the timestamp to UTC format in Pyspark 问题与问题类似: 在Pyspark中将时间戳更改为UTC格式

Basically, it is convert timestamp string format ISO8601 with offset to UTC timestamp string( 2017-08-01T14:30:00+05:30 -> 2017-08-01T09:00:00+00:00 ) using scala . 基本上,它使用scala将具有偏移量的时间戳字符串格式ISO8601转换为UTC时间戳字符串( 2017-08-01T14:30:00+05:30 > 2017-08-01T09:00:00+00:00 )。

I am kind of new to scala/java, I checked spark library which they dont have a way to convert without knowing the timezone, which I dont have a idea of timezone unless (I parse it in ugly way or using java/scala lib?) Can someone help? 我是scala / java的新手,我检查了spark库,他们没有不知道时区的方式就无法转换,除非没有(我以丑陋的方式或使用java / scala lib解析它),否则我不知道时区。 )有人可以帮忙吗?

UPDATE: The better way to do this: setup timezone session in spark, and use df.cast(DataTypes.TimestampType) to do the timezone shift 更新:做到这一点的更好方法:在spark中设置时区会话,并使用df.cast(DataTypes.TimestampType)进行时区转换

You can use the java.time primitives to parse and convert your timestamp. 您可以使用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 : 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. 给定类似“ 2017-07-14 02:40:00.0”的时间戳,将其解释为给定时区中的时间,并将该时间呈现为UTC中的时间戳。 For example, 'GMT+1' would yield '2017-07-14 01:40:00.0'. 例如,“ GMT + 1”将产生“ 2017-07-14 01:40:00.0”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM