【问题标题】:Redshift (SQL): try convert to timestampRedshift (SQL):尝试转换为时间戳
【发布时间】:2016-10-13 19:34:03
【问题描述】:

我有一列带有时间戳作为字符串,如下所示:

starttime             | attribute
2000-08-21T23:10:37Z  | X

现在我想将这些字符串转换为 AWS Redshift 中的正确时间戳。 以下适用于上述示例中显示的行,

 CAST(starttime as timestamp)

但有些行的格式不正确,因此引发异常:

 error:  Invalid data
 code:      8001
 context:   Invalid format or data given:    

有没有办法使用类似于 MS SQL 服务器中的 try_convert 的东西? 我尝试了以下方法但没有取得多大成功:

case when starttime ~ '\d{1,4}-\d{1,2}-\d{1,2}T\d{1,2}:\d{1,2}:\d{1,2}Z' 
then cast(starttime as timestamp) else null end

但是这个正则表达式不起作用..还尝试使用 [[:digit:]] 代替 \d 或 \d,但没有任何效果..

明确一点:我知道某些行包含错误数据,因此我不担心将它们排除在外。

【问题讨论】:

  • 我鼓励您通过更改加载脚本将正确的数据类型加载到红移,以便轻松执行任何日期操作。此外,尝试 Pythonic 版本的 Redshift UDF 来解析这些条件。 Redshift UDF 方法创建了与 SQL 无关的解决方案,并且可以很好地扩展以支持开箱即用的多种日期格式。
  • @kadalamittai 感谢您的反馈,UDF 看起来很有前途,很快就会使用它们。

标签: sql string casting timestamp amazon-redshift


【解决方案1】:

您遗漏了一个小细节:将所有 \ds 更改为 \\d。根据文档here:

Amazon Redshift 在正则表达式中支持以下受 Perl 影响的运算符。使用两个反斜杠 ('\') 转义运算符。

我尝试了以下方法:

create temp table v (starttime varchar(255));
insert into v values ('2000-08-21T23:10:37Z'), ('ddd');

-- the next line doesn't work, as you yourself suggested.
select CAST(starttime as timestamp) from v;
-- the next line works.
select case when starttime ~ '\\d{1,4}-\\d{1,2}-\\d{1,2}T\\d{1,2}:\\d{1,2}:\\d{1,2}Z' then cast(starttime as timestamp) else null end from v;

【讨论】:

【解决方案2】:

如果您从字符串中删除 T 并替换为可以转换的空格

CAST(replace(starttime, 'T', ' ') as timestamp)

【讨论】:

    猜你喜欢
    • 2017-11-11
    • 2020-05-30
    • 2018-01-07
    • 2020-10-17
    • 1970-01-01
    • 2016-07-23
    • 2015-05-28
    • 2019-08-11
    • 1970-01-01
    相关资源
    最近更新 更多