问题描述
如何在 spark 中将字符串 2018-03-21 08:15:00 +03:00
存储为 timestamptype
,同时保留 UTC 偏移量?
尝试过
from pyspark.sql.functions import *
df = spark.createDataFrame([("2018-03-21 08:15:00 +03:00",)],["timestamp"])
newDf= df.withColumn("newtimestamp",to_timestamp(col('timestamp'),"yyyy-MM-dd HH:mm:ss XXX")
)
这会打印 newtimestamp
列,其值转换为 UTC 时间,即 2018-03-21 05:15:00
如何将此字符串作为时间戳列存储在保留偏移量的数据帧中,即存储与时间戳相同的字符串或像 2018-03-21 08:15:00 +3000
一样存储
解决方法
您需要使用 date_format
将您从转换中获得的时间戳格式化为所需的模式:
newDf = df.withColumn(
"newtimestamp",to_timestamp(col('timestamp'),"yyyy-MM-dd HH:mm:ss XXX")
).withColumn(
"newtimestamp_formatted",date_format("newtimestamp","yyyy-MM-dd HH:mm:ss Z")
)
newDf.show(truncate=False)
#+--------------------------+-------------------+-------------------------+
#|timestamp |newtimestamp |newtimestamp_formatted |
#+--------------------------+-------------------+-------------------------+
#|2018-03-21 08:15:00 +03:00|2018-03-21 06:15:00|2018-03-21 06:15:00 +0100|
#+--------------------------+-------------------+-------------------------+