我正在使用 Pyspark,我的输入数据包含一个时间戳列(包含时区信息)
2012-11-20T17:39:37Z
我想创建此时间戳的 America/New_York
表示。我的理解是,最好的工具是 from_utc_timestamp
。尽管当我使用它时,我得到了不合理的结果。
F.from_utc_timestamp(F.col('ts'), 'America/New_York')
>>> datetime.datetime(2012, 11, 20, 7, 39, 37)
应该是什么时候
datetime.datetime(2012, 11, 20, 12, 39, 37)
来自 from_utc_timestamp 的 doc我明白了
This function may return confusing result if the input is a string with timezone, e.g. ‘2018-03-13T06:18:23+00:00’. The reason is that, Spark firstly cast the string to timestamp according to the timezone in the string, and finally display the result by converting the timestamp to string according to the session local timezone.
所以我认为包含 tzinfo 的时间戳和不天真是罪魁祸首。但是我找不到从时间戳中删除此信息的好方法。
免责声明 - 1. 我不想为此依赖 UDF 2. 我无法更改 SparkSession
时区,因为这不是专用于此作业的集群。
有什么想法吗?
最佳答案
将 SparkSession
时区指向 UTC
应该会给您所需的结果。
spark.conf.set('spark.sql.session.timeZone', 'UTC')
spark.sql("""select from_utc_timestamp('2012-11-20T17:39:37Z', 'America/New_York') as datetime""" ).show(truncate=False)
'''
+-------------------+
|datetime |
+-------------------+
|2012-11-20 12:39:37|
+-------------------+'''
或者,您可以将时区设置为 America/New_York
并使用 to_timestamp()
。
spark.conf.set('spark.sql.session.timeZone', 'America/New_York')
spark.sql("""select to_timestamp('2012-11-20T17:39:37Z', "yyyy-MM-dd'T'HH:mm:ssz") as datetime""").show(truncate=False)
'''
+-------------------+
|datetime |
+-------------------+
|2012-11-20 12:39:37|
+-------------------+'''
关于apache-spark - 如何将不同的时区应用于 PySpark 中的时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68956623/