跳过格式错误的日期分析预处理

b4wnujal  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(298)

我使用下面的查询来解析presto中的日期: SELECT date_parse(t.up_date, '%c/%e/%Y %l:%i:%s %p') from table t 样本日期为: 4/11/2021 12:30:00 PM 但有时我们得到的日期不是不能像这样解析的 "testdate" (任何不是日期的字符串)
如何在查询中跳过这些日期?我的查询应该如下所示:

select date_parse(t.up_date, '%c/%e/%Y %l:%i:%s %p') 
     from table t 
    where <skip the date that does not parse>
pvcm50d1

pvcm50d11#

使用 try() . 正常情况下 date_parse() 错误的日期格式失败。如果你加上 try() ,它将产生 NULL 对于错误的日期,过滤空记录,如下所示:

select try(date_parse(t.up_date, '%c/%e/%Y %l:%i:%s %p'))
  from table t 
 where try(date_parse(t.up_date, '%c/%e/%Y %l:%i:%s %p')) is not NULL

您还可以尝试使用coalesce()解析不同的格式,以选择成功解析的格式:

select
      coalesce( try(date_parse(t.up_date, '%c/%e/%Y %l:%i:%s %p')), --try format1
                try(date_parse(t.up_date, '%Y/%m/%d'))  --try format2
              )
 from table t 
where --filter only parsed dates
     coalesce( try(date_parse(t.up_date, '%c/%e/%Y %l:%i:%s %p')), --try format1
               try(date_parse(t.up_date, '%Y/%m/%d'))  --try format2
              ) is not NULL;

通过这种方式,您可以尝试解析数据中可能存在的不同格式。

相关问题