简体   繁体   中英

Converting a date to a numeric timestamp in Snowflake

I have a query wherein one of the columns is a DATE type. I'm trying to convert that to the nanosecond representation of the timestamp associated with the date:

Input Output
2022-07-15 1657843200000000000
2022-07-18 1658102400000000000
2022-07-19 1658188800000000000

I can get a timestamp from a date by doing this:

SELECT TRY_TO_TIMESTAMP(TO_VARCHAR($1))
FROM (
    SELECT DATE($1) FROM VALUES ('2022-07-15'), ('2022-07-18'), ('2022-07-19'))

but using TRY_TO_NUMERIC doesn't work so I'm not sure what to do here.

You can use the datediff function to return the nanoseconds since the start of the Unix epoch, which is 1970-01-01:

with source_data as
(
    select 
    COLUMN1::date as INPUT
    from (values
    ('2022-07-15'),
    ('2022-07-18'),
    ('2022-07-19')
    )
)
select   INPUT
        ,datediff(nanoseconds, '1970-01-01'::date, INPUT) as OUTPUT
from SOURCE_DATA
;
INPUT OUTPUT
2022-07-15 1657843200000000000
2022-07-18 1658102400000000000
2022-07-19 1658188800000000000

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM