跳过格式错误的日期解析 presto

问题描述

我正在使用以下查询来解析 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>

解决方法

使用try()。 通常 date_parse() 因日期格式错误而失败。如果您添加 try(),它将为错误的日期生成 NULL,您可以像这样过滤 NULL 记录:

select try(date_parse(t.up_date,'%c/%e/%Y %l:%i:%s %p'))
  from table t 
  --filter rows wich can not be parsed if necessary
 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,--try format1
               try(date_parse(t.up_date,'%Y/%m/%d'))  --try format2
              ) is not NULL;

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...