繁体   English   中英

Pyspark DD-MMM-YYYY(字符串格式)到时间戳

[英]Pyspark DD-MMM-YYYY (string format) to timestamp

您好,我是 Pyspark 的新手,我有一个包含日期 DD-MMM-YYYY 格式的字符串变量,我想将其转换为时间戳?

24-MAY-2019 - 时间戳的字符串格式

尝试使用to_timestamp(preferred) (or) from_unixtime and unix_timestamp函数:

Example:

from pyspark.sql.functions import *
from pyspark.sql.types import *
df.selectExpr("to_timestamp(dt,'dd-MMM-yyyy') as tt").show()
+-------------------+
|                 tt|
+-------------------+
|2019-05-24 00:00:00|
+-------------------+

df1.withColumn("ts",to_timestamp(col("dt"),'dd-MMM-yyyy')).show()
+-----------+-------------------+
|         dt|                 ts|
+-----------+-------------------+
|24-MAY-2019|2019-05-24 00:00:00|
+-----------+-------------------+

#using from_unixtime and unix_timestamp
df1.withColumn("ts",from_unixtime(unix_timestamp(col("dt"),'dd-MMM-yyyy'),'yyyy-MM-dd HH:mm:ss.SSS').cast("timestamp")).show(10,False)
+-----------+-----------------------+
|dt         |ts                     |
+-----------+-----------------------+
|24-MAY-2019|2019-05-24 00:00:00.000|
+-----------+-----------------------+

#using unix_timestamp and casting to timestamp
df1.withColumn("ts",unix_timestamp(col("dt"),'dd-MMM-yyyy').cast("timestamp")).show()
#+-----------+-------------------+
#|         dt|                 ts|
#+-----------+-------------------+
#|24-MAY-2019|2019-05-24 00:00:00|
#+-----------+-------------------+

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM