我在 pySpark 数据框中有一列 date
,日期格式如下:
2018-02-01T13:13:12.023507
我想将该列中的日期从字符串转换为时间戳(或者我可以根据日期对其进行排序的内容)。到目前为止,我已经尝试了以下方法:
new_df = df.withColumn(
'date',
unix_timestamp("date", "YYYY-MM-DD'T'hh:mm:ss.s").cast("double").cast("timestamp")
)
还有这个
new_df = df.withColumn(
'date',
from_unixtime(
unix_timestamp(col(('date')), "yyyy-MM-dd'T'hh:mm:ss.SSS"),
"yyyy-MM-dd'T'HH:mm:ss.SSS"
)
)
还有这个
df_new = df.withColumn(
'date1',
F.to_timestamp("date", "yyyy-dd-MM'T'hh:mm:ss.s")
)
我尝试了在其他类似问题中发现的所有内容,但到目前为止没有任何效果。我还尝试了一种不同的格式 yyyy-MM-dd'T'HH:mm:ss.ssssss
但没有成功。我错过了什么?
最佳答案
对于 Spark >= 2.2,unix_timestamp()
的替代方法是使用 to_timestamp()
:
from pyspark.sql.functions import col, to_timestamp
new_df = df.withColumn('converted_date',to_timestamp(col('date'), "yyyy-MM-dd'T'HH:mm:ss"))
关于pyspark - 将日期字符串转换为时间戳以按亚秒精度排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55518697/