在spark中将任何日期格式转换为dd-mm-yyyy hh:mm:ss

vatpfxk5  于 2021-06-25  发布在  Hive
关注(0)|答案(2)|浏览(333)

这个问题在这里已经有答案了

将包含多个字符串日期格式的列强制转换为spark中的datetime(2个答案)
一年前关门了。
我有一个包含日期列的文件。它包含多种格式的日期。我得把所有的都转换成 DD-MM-YYYY hh:mm:ss .
写入以下查询,但未得到预期结果:-

scala> val a = Seq(("01-Jul-2019"),("01-Jul-2019 00:01:05"),("Jul-01-2019"),("2019-07-01")).toDF("create_dts").select(col("create_dts"))
a: org.apache.spark.sql.DataFrame = [create_dts: string]

scala>

scala> val r = a.withColumn("create_dts", date_format(to_timestamp($"create_dts", "dd-MMM-yyyy").cast("timestamp"), "dd-MM-yyyy hh:mm:ss")).show

+-------------------+
|         create_dts|
+-------------------+
|01-07-2019 12:00:00|
|01-07-2019 12:00:00|
|               null|
|               null|
+-------------------+
xsuvu9jc

xsuvu9jc1#

它现在使用的很好 when 条件

val a = Seq(("01-Jul-2019"),("01-07-2019")).toDF("create_dts")
val r = a.withColumn("create_dts",when(to_timestamp($"create_dts", "dd-MMM-yyyy").cast("date").isNotNull,date_format(to_timestamp($"create_dts", "dd-MMM-yyyy").cast("date"), "dd-MM-yyyy")).when(to_timestamp($"create_dts", "dd-MM-yyyy").cast("date").isNotNull,date_format(to_timestamp($"create_dts", "dd-MM-yyyy").cast("date"), "dd-MM-yyyy")))
uidvcgyl

uidvcgyl2#

你可以用 coalesce 获取第一个非空转换的函数:

import org.apache.spark.sql.Column

def to_timestamp_multiple(s: Column, formats: Seq[String]): Column = {
    coalesce(formats.map(fmt => to_timestamp(s, fmt)):_*)
}
a.withColumn("converted", date_format(to_timestamp_multiple($"create_dts",
      Seq("dd-MMM-yyyy", "MMM-dd-yyyy", "yyyy-MM-dd"))
    .cast("timestamp"), "dd-MM-yyyy hh:mm:ss")).show

结果是:

+--------------------+-------------------+
|          create_dts|          converted|
+--------------------+-------------------+
|         01-Jul-2019|01-07-2019 12:00:00|
|01-Jul-2019 00:01:05|01-07-2019 12:00:00|
|         Jul-01-2019|01-07-2019 12:00:00|
|          2019-07-01|01-07-2019 12:00:00|
+--------------------+-------------------+

相关问题