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:mm
和 yyyy-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
输出:
strt_tm
2021-12-11 01:15
2021-12-11 11:15
使用 coalesce
处理两种格式以及 to_timestamp
or to_date
函数:
spark.createDataFrame(
[("12/11/21 01:15",), ("2021-12-11 11:15:12",)], ["strt_tm"]
).createOrReplaceTempView("table1")
spark.sql("""
select coalesce(
to_timestamp(strt_tm, 'dd/MM/y HH:mm'),
to_timestamp(strt_tm, 'yyyy-MM-dd HH:mm:ss')
) as start_time,
coalesce(
to_date(strt_tm, 'dd/MM/y HH:mm'),
to_date(strt_tm, 'yyyy-MM-dd HH:mm:ss')
) as start_date
from table1
""").show()
#+-------------------+----------+
#| start_time|start_date|
#+-------------------+----------+
#|2021-11-12 01:15:00|2021-11-12|
#|2021-12-11 11:15:12|2021-12-11|
#+-------------------+----------+
我在开始时间有 2 种日期格式(MM/dd/yy HH:mm
和 yyyy-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
输出:
strt_tm
2021-12-11 01:15
2021-12-11 11:15
使用 coalesce
处理两种格式以及 to_timestamp
or to_date
函数:
spark.createDataFrame(
[("12/11/21 01:15",), ("2021-12-11 11:15:12",)], ["strt_tm"]
).createOrReplaceTempView("table1")
spark.sql("""
select coalesce(
to_timestamp(strt_tm, 'dd/MM/y HH:mm'),
to_timestamp(strt_tm, 'yyyy-MM-dd HH:mm:ss')
) as start_time,
coalesce(
to_date(strt_tm, 'dd/MM/y HH:mm'),
to_date(strt_tm, 'yyyy-MM-dd HH:mm:ss')
) as start_date
from table1
""").show()
#+-------------------+----------+
#| start_time|start_date|
#+-------------------+----------+
#|2021-11-12 01:15:00|2021-11-12|
#|2021-12-11 11:15:12|2021-12-11|
#+-------------------+----------+