将日光节约时间字符串转换为时间戳会给出错误的结果

Converting day lights savings time string to timestamp gives wrong results

我有一个 pyspark 数据框。在这个数据框中,我有一个名为 test_time 的列,它是 string 数据类型

>>> df
DataFrame[test_time: string]

df.show()

+-------------------+
|          test_time|
+-------------------+
|2017-03-12 02:41:06|
|2017-03-12 02:43:52|
|2017-03-12 02:56:32|
|2017-03-12 03:16:23|
|2017-03-12 03:17:15|
|2017-03-12 03:22:19|
|2017-03-12 03:52:19|
|2017-03-12 04:03:21|
+-------------------+

现在我想将此 test_time 列从 string 转换为 timestamp

我已经像下面那样做了

from pyspark.sql import functions as F
df1 = df.withColumn('convert_test', F.unix_timestamp('test_time', "yyyy-MM-dd hh:mm:ss").cast('timestamp'))

>>> df1
DataFrame[test_time: string, convert_test: timestamp]

df1.show()

+-------------------+--------------------+
|          test_time|        convert_test|
+-------------------+--------------------+
|2017-03-12 02:41:06|2017-03-12 03:41:...|
|2017-03-12 02:43:52|2017-03-12 03:43:...|
|2017-03-12 02:56:32|2017-03-12 03:56:...|
|2017-03-12 03:16:23|2017-03-12 03:16:...|
|2017-03-12 03:17:15|2017-03-12 03:17:...|
|2017-03-12 03:22:19|2017-03-12 03:22:...|
|2017-03-12 03:52:19|2017-03-12 03:52:...|
|2017-03-12 04:03:21|2017-03-12 04:03:...|
+-------------------+--------------------+

如您所见,Hours1-3 不同。

FYI 我的时区是 PST1-3day light savings 时间段内的时间。

我怎样才能完成正确的转换。

我使用 unix_timestamp()

得到了正确的输出
  val dataframe = Seq(
    ("2017-03-12 02:41:06"),
    ("2017-03-12 02:43:52"),
    ("2017-03-12 02:56:32"),
    ("2017-03-12 03:16:23"),
    ("2017-03-12 03:17:15"),
    ("2017-03-12 03:22:19"),
    ("2017-03-12 03:52:19"),
    ("2017-03-12 04:03:21")
  ).toDF("test_time")

 dataframe.withColumn("convert_test", unix_timestamp($"test_time", "yyyy-MM-dd hh:mm:ss").cast("timestamp")).show()

输出:

+-------------------+--------------------+
|          test_time|        convert_test|
+-------------------+--------------------+
|2017-03-12 02:41:06|2017-03-12 02:41:...|
|2017-03-12 02:43:52|2017-03-12 02:43:...|
|2017-03-12 02:56:32|2017-03-12 02:56:...|
|2017-03-12 03:16:23|2017-03-12 03:16:...|
|2017-03-12 03:17:15|2017-03-12 03:17:...|
|2017-03-12 03:22:19|2017-03-12 03:22:...|
|2017-03-12 03:52:19|2017-03-12 03:52:...|
|2017-03-12 04:03:21|2017-03-12 04:03:...|
+-------------------+--------------------+

如果您处于不同的时区,则可以使用 from_utc_timestamp()to_utc_timestamp() 等函数来转换时间戳。

希望对您有所帮助!