问题描述
我正在使用以下查询来解析 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;
通过这种方式,您可以尝试解析数据中可能存在的不同格式。