Timestamp to epoch conversion in teradata

倖福魔咒の 提交于 2019-12-02 05:55:55

This is a SQL UDF I wrote a few years ago.

If you don't have access rights to create a function, you mighty ask you dab or simply cut & paste the calculation.

/**********
Converting a Timestamp to Unix/POSIX/epoch time

Unix time: Number of seconds since 1970-01-01 00:00:00 UTC not counting leap seconds (currently 34 in 2010)

The maximum range of Timestamps is based on the range of INTEGERs:
1901-12-13 20:45:52 (-2147483648) to 2038-01-19 03:14:07 (2147483647)

Simply change to BIGINT to cover the full Teradata date range

20101211 initial version - Dieter Noeth
**********/
REPLACE FUNCTION TimeStamp_to_UnixTime (ts TIMESTAMP(6))
RETURNS INT
LANGUAGE SQL
CONTAINS SQL
DETERMINISTIC
SQL SECURITY DEFINER
COLLATION INVOKER
INLINE TYPE 1
RETURN 
(CAST(ts AS DATE) - DATE '1970-01-01') * 86400
+ (EXTRACT(HOUR FROM ts) * 3600)
+ (EXTRACT(MINUTE FROM ts) * 60)
+ (EXTRACT(SECOND FROM ts))
;

Reversing the calculation:

/**********
Converting Unix/POSIX/epoch time to a Timestamp 

Unix time: Number of seconds since 1970-01-01 00:00:00 UTC not counting leap seconds (currently 34 in 2010)

Also working for negative numbers.
The maximum range of Timestamps is based on the range of INTEGERs:
1901-12-13 20:45:52 (-2147483648) to 2038-01-19 03:14:07 (2147483647)

Simply change to BIGINT to cover the full Teradata date range

20101211 initial version - Dieter Noeth
**********/

REPLACE FUNCTION UnixTime_to_TimeStamp (UnixTime INT)
RETURNS TimeStamp(0)
LANGUAGE SQL
CONTAINS SQL
DETERMINISTIC
SQL SECURITY DEFINER
COLLATION INVOKER
INLINE TYPE 1
RETURN 
CAST(DATE '1970-01-01' + (UnixTime / 86400) AS TIMESTAMP(0))
+ ((UnixTime MOD 86400) * INTERVAL '00:00:01' HOUR TO SECOND)
;

It's is easier in TD14 using TO_TIMESTAMP(UnixTime), but this is restricted to the INTEGER range.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!