繁体   English   中英

pyspark sql 将日期格式从 mm/dd/yy hh:mm 或 yyyy-mm-dd hh:mm:ss 转换为 yyyy-mm-dd hh:mm 格式

[英]pyspark sql convert date format from mm/dd/yy hh:mm or yyyy-mm-dd hh:mm:ss into yyyy-mm-dd hh:mm format

我在开始时间有 2 种日期格式( MM/dd/yy HH:mmyyyy-mm-dd HH:mm:ss )需要转换为yyyy-mm-dd HH:mm格式。 如何在 select 语句下处理两种数据格式以转换为所需格式

df1 = spark.sql("""select from_unixtime(unix_timestamp(strt_tm,'MM/dd/yy HH:mm'),'yyyy-mm-dd HH:mm) as starttime from table1""")

输入

strt_tm          
12/11/21 01:15
2021-12-11 11:15:12

output:

strt_tm 
2021-12-11 01:15
2021-12-11 11:15

使用coalesce处理带有to_timestamp的两种格式,然后使用date_format function 格式化结果:

spark.createDataFrame(
    [("12/11/21 01:15",), ("2021-12-11 11:15:12",)], ["strt_tm"]
).createOrReplaceTempView("table1")

spark.sql("""
select date_format(
            coalesce(
                to_timestamp(strt_tm, 'dd/MM/y HH:mm'), 
                to_timestamp(strt_tm, 'yyyy-MM-dd HH:mm:ss')
            ),
            'yyyy-MM-dd HH:mm'
        ) as starttime
from table1
""").show()

#+----------------+
#|       starttime|
#+----------------+
#|2021-11-12 01:15|
#|2021-12-11 11:15|
#+----------------+

暂无
暂无

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

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