在Redshift中从字符串中提取日期和时间

时间:2019-08-16 21:12:33

标签: amazon-redshift

我有一列像下面这样。最后两组数字是日期和时间。我想通过从列中提取值来创建日期时间列。

  

1002206391240385-sponsoredProducts-SameDayPull-20190627-012313.json

从提取日期开始,但是没有给出我所需要的

Select regexp_substr('1002206391240385-sponsoredProducts-SameDayPull-20190627-012313.json','-[\\d{8}]-')

2 个答案:

答案 0 :(得分:1)

此子字符串从您的字符串中提取日期时间部分。

SELECT substring(col_name,regexp_instr(col_name,'-',1,regexp_count(col_name,'-')-1)+1,
                 regexp_instr(col_name,'.json',1)-regexp_instr(col_name,'-',1,regexp_count(col_name,'-')-1)-1)

regexp_count计数在字符串中有许多连字符

regexp_instr给出连字符的位置

substring返回从秒到最后一个连字符,直到字符串中的 .json

要测试我用过

WITH test(col_name) AS (
SELECT '1002206391240385-sponsoredProducts-SameDayPull-20190627-012313.json'::TEXT
)
SELECT col_name,
substring(col_name,regexp_instr(col_name,'-',1,regexp_count(col_name,'-')-1)+1,
                  regexp_instr(col_name,'.json',1)-regexp_instr(col_name,'-',1,regexp_count(col_name,'-')-1)-1) datetime
FROM test

输出为

col_name                                                            datetime
1002206391240385-sponsoredProducts-SameDayPull-20190627-012313.json 20190627-012313

答案 1 :(得分:0)

或者,如果文件名格式一致,则可以使用非正则表达式解决方案,例如提取文件名字符串中包含日期的部分,然后将TO_TIMESTAMPformat string一起使用以提取日期和时间:

SELECT TO_TIMESTAMP(RIGHT('1002206391240385-sponsoredProducts-SameDayPull-20190627-012313.json', 20), 'YYYYMMDD-HH24MISS.json')  AS extracted_datetime

返回

extracted_datetime    |
----------------------|
2019-06-27 01:23:13+00|