我在開始時間有 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
uj5u.com熱心網友回復:
使用coalesce與沿處理這兩種格式to_timestamp或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|
# ------------------- ----------
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/405135.html
標籤:
