将日期字符串转换为时间戳以进行亚秒级精度排序 [英] Convert date string to timestamp for sorting on sub-second precision
问题描述
我在 pySpark 数据框中有一列 date
,日期格式如下:
I have a column date
in a pySpark dataframe with dates in the following format:
2018-02-01T13:13:12.023507
我想将该列中的日期从字符串转换为时间戳(或者我可以根据日期对其进行排序).到目前为止,我已经尝试了以下内容:
I want to convert the dates in that column from string to timestamp (or something that I can sort it based on the date). So far I have tried the following:
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
没有成功.我错过了什么?
I tried everything I found in other similar questions but so far nothing is working. I have also tried a different format yyyy-MM-dd'T'HH:mm:ss.ssssss
with no success. What am I missing?
推荐答案
对于 Spark >= 2.2 来说,unix_timestamp()
的替代方法是使用 to_timestamp()
:
for Spark >= 2.2 an alternative approach to unix_timestamp()
is by using 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"))
这篇关于将日期字符串转换为时间戳以进行亚秒级精度排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!