PySpark(版本 3.0.0) 当我event_timestamp列从字符串转换为时间戳时,to_timestamp



输入文件格式:https://i.stack.imgur.com/aNDmZ.png

转换后:https://i.stack.imgur.com/nobwD.png

我尝试了堆栈溢出的其他解决方案,但我使用的是 spark 3.0.0 并且它不起作用。

to_timestamp中,您需要使用ahh而不是HH来匹配AM/PM

Example:

sc.version
#'3.0.0-preview2'
df.show()
#+-------------------+
#|    event_timestamp|
#+-------------------+
#|10/14/2016 09:28 PM|
#|10/23/2016 02:41 AM|
#+-------------------+
from pyspark.sql.functions import *
#using to_timestamp function
df.withColumn("new_ts",to_timestamp(col("event_timestamp"),"MM/dd/yyyy hh:mm a")).show()
#using from_unixtime and unix_timestmap functions
df.withColumn("new_ts",from_unixtime(unix_timestamp(col("event_timestamp"),"MM/dd/yyyy hh:mm a"),'yyyy-MM-dd HH:mm:ss').cast("timestamp")).show()
#+-------------------+-------------------+
#|    event_timestamp|             new_ts|
#+-------------------+-------------------+
#|10/14/2016 09:28 PM|2016-10-14 21:28:00|
#|10/23/2016 02:41 AM|2016-10-23 02:41:00|
#+-------------------+-------------------+

def to_timestamp(s: Column, fmt: String(: Column 将具有给定模式的时间字符串转换为时间戳。

有关有效的日期和时间格式模式,请参阅日期时间模式

s 日期、时间戳或字符串。如果是字符串,则数据必须采用可强制转换为时间戳的格式,例如 yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss。SSSS

FMT 当 s 是字符串时详细说明 s 格式的日期时间模式

返回 时间戳,如果 s 是无法转换为时间戳的字符串或 fmt 格式无效,则为 null

因为 2.2.0

最新更新