从 Pyspark 中的字符串类型转换为时间戳

问题描述 投票:0回答:1

如何在 Pyspark 中将字符串类型转换为时间戳 string类型数据是这样的2024-04-02-19.02.20.000000。我需要时间戳中的此列数据。

Column为String类型,需要转入时间戳

apache-spark pyspark
1个回答
0
投票

您可以使用

to_timestamp
功能和自定义模式来适应您的格式:

from pyspark.sql.functions import *

df = spark.createDataFrame([(1, "2023-04-15-19.20.20.000000"), (2, "2023-10-02-19.02.20.000000"), (3, "2024-04-02-19.02.20.000000")], ("id", "dt"))

df.withColumn("pdt", to_timestamp("dt", "yyyy-MM-dd-HH.mm.ss.SSSSSS")).show()
+---+--------------------+-------------------+
| id|                  dt|                pdt|
+---+--------------------+-------------------+
|  1|2023-04-15-19.20....|2023-04-15 19:20:20|
|  2|2023-10-02-19.02....|2023-10-02 19:02:20|
|  3|2024-04-02-19.02....|2024-04-02 19:02:20|
+---+--------------------+-------------------+
© www.soinside.com 2019 - 2024. All rights reserved.