SQL 雪花日期的正确类型

correct type for SQL snowflake date

我正在使用 SQL 脚本使用 dbt 将 json 解析为 table。其中一个列具有此日期值:“2022-02-09T20:28:59+0000”。在 Snowflake 中定义 iso date 数据类型的正确方法是什么?

目前,我只是在我的 dbt sql 脚本中使用了这样的 date 类型:

JSON_DATA:"situation_date"::date AS MY_DATE

但很明显,date 不是正确的,因为稍后当我使用 select * 测试它时,我得到了这个错误:

SQL Error [100040] [22007]: Date '2022-02-09T20:28:59+0000' is not recognized

所以我需要知道哪种 Snowflake 日期数据类型或日期时间类型最适合这个

使用TRY_TO_TIMESTAMP

SELECT TRY_TO_TIMESTAMP(JSON_DATA:"situation_date", 'format_here')
FROM tab;

so I need to know which Snowflake date data type or datetime type suits the best with this one

TIMESTAMP_INPUT_FORMAT

可以在ACCOUNT/USER/SESSION级别上设置特定的输入。

AUTO Detection of Integer-stored Date, Time, and Timestamp Values

Avoid using AUTO format if there is any chance for ambiguous results. Instead, specify an explicit format string by:

Setting TIMESTAMP_INPUT_FORMAT and other session parameters for dates, timestamps, and times. See Session Parameters for Dates, Times, and Timestamps (in this topic).

我认为 ::TIMESTAMP 应该适用于此。所以 JSON_DATA:"situation_date"::TIMESTAMP 如果你需要在之后约会,你可以 ::Dateto_Date()

正确拉出“来自 JSON 的日期”,所以不是很清楚:

SELECT
    '{"date":"2022-02-09T20:28:59+0000"}' as json_str
    ,parse_json(json_str) as json
    ,json:date as data_from_json
    ,TRY_TO_TIMESTAMP_NTZ(data_from_json, 'YYYY-MM-DDTHH:MI:SS+0000') as date_1
    ,TRY_TO_TIMESTAMP_NTZ(substr(data_from_json,1,19), 'YYYY-MM-DDTHH:MI:SS') as date_2
    ;

给出错误:

Function TRY_CAST cannot be used with arguments of types VARIANT and TIMESTAMP_NTZ(9)

因为 data_from_json 的类型为 VARIANT 并且 TO_DATE/TO_TIMESTAMP 函数期望 TEXT 所以我们需要转换为

SELECT
    '{"date":"2022-02-09T20:28:59+0000"}' as json_str
    ,parse_json(json_str) as json
    ,json:date as data_from_json
    ,TRY_TO_TIMESTAMP_NTZ(data_from_json::text, 'YYYY-MM-DDTHH:MI:SS+0000') as date_1
    ,TRY_TO_TIMESTAMP_NTZ(substr(data_from_json::text,1,19), 'YYYY-MM-DDTHH:MI:SS') as date_2
    ;

如果你所有的时区总是+0000你可以把它放在解析格式中(比如例子date_1),或者你可以截断那部分(比如例子date_2 )

给出:

JSON_STR JSON DATA_FROM_JSON DATE_1 DATE_2
{"date":"2022-02-09T20:28:59+0000"} { "date": "2022-02-09T20:28:59+0000" } "2022-02-09T20:28:59+0000" 2022-02-09 20:28:59.000 2022-02-09 20:28:59.000

经过一些测试,在我看来你有 2 个选择。

要么把最后的+0000去掉:
left(column_date, len(column_date)-5)::timestamp

或使用函数 try_to_timestamp 格式:
try_to_timestamp('2022-02-09T20:28:59+0000','YYYY-MM-DD"T"HH24:MI:SS+TZHTZM')

TZHTZM 都是 TimeZone Offset Hours and Minutes