日期時間資料型別

Snowflake 的資料型別與函式

Jake Roach

Field Data Engineer

DATE 資料型別

  • Date 值會儲存事件發生的那一天
                            2023-04-01
                            YYYY-MM-DD
  CREATE TABLE sales (
      transaction_date DATE  -- Define a column of type `DATE`
  );
Snowflake 的資料型別與函式

DATE 資料型別

SELECT

TO_DATE('2023-04-01') AS the_date, -- Convert a string into a DATE
'2023-04-01'::DATE AS casted_date -- Casted using <value>::DATE
;
                         the_date  | casted_date  
                       ----------- | ------------  
                        2023-04-01 | 2023-04-01
Snowflake 的資料型別與函式

Time 資料型別

  • 擷取事件發生的時、分、秒
                               08:24:08
                               HH:MM:SS
CREATE TABLE sales (
    transaction_time TIME  -- Create a column with the `TIME` keyword
);
  • 定義 TIME 欄位
Snowflake 的資料型別與函式

Time 資料型別

SELECT

TO_TIME('08:24:04') AS the_time,
'08:24:04'::TIME AS casted_time
;
                     |  the_time  | casted_time |
                     | ---------- | ----------- |
                     |  08:24:08  |  08:24:08   |
  • TO_TIME 函式
  • 使用 :: 轉型
Snowflake 的資料型別與函式

Timestamp 資料型別

  • TIMESTAMP 同時擷取日期與時間
                        2023-04-01 08:24:04
                        YYYY-MM-DD HH:MM:SS
CREATE TABLE (
    transaction_timestamp TIMESTAMP
);
Snowflake 的資料型別與函式

Timestamp 資料型別

SELECT 
    TO_TIMESTAMP('2023-04-01 08:24:04') AS the_timestamp,
    '2023-04-01 08:24:04'::TIMESTAMP AS casted_timestamp          
;
  • 使用 TO_TIMESTAMP<value>::TIMESTAMP 將字串轉為 timestamp
  • 最常見的日期時間儲存方式
                  the_timestamp     |    casted_timestamp     
              --------------------- | ----------------------  
               2024-04-01 08:24:08  |  2024-04-01 08:24:08    
Snowflake 的資料型別與函式

範例

SELECT
    TO_DATE('2021-05-14') AS the_date,
    TO_TIME('06:13:00') AS the_time,
    TO_TIMESTAMP('2021-05-14T06:13:00') AS the_timestamp,


-- Extract the DATE from a TIMESTAMP, we could do the same with TIME! transaction_timestamp::DATE AS casted_date
;
           the_date   |   the_time  |     the_timestamp    | casted_date  
         ------------ | ----------- | -------------------- | ------------  
          2021-05-14  |   06:13:00  | 2021-05-14T06:13:00  |  2021-05-14
Snowflake 的資料型別與函式

時區

預設情況下,DATETIMETIMESTAMP 皆不含時區

$$

TIMESTAMP_NTZ

  • TIMESTAMP 的預設實作
  • 不儲存時區

$$

TIMESTAMP_LTZ

  • 依據本機時區

$$

TIMESTAMP_TZ

  • 使用者可指定時區
1 https://docs.snowflake.com/en/sql-reference/data-types-datetime#timestamp-ltz-timestamp-ntz-timestamp-tz
Snowflake 的資料型別與函式

一起來練習吧!

Snowflake 的資料型別與函式

Preparing Video For Download...