teradata中时间转换的时间戳

时间:2014-08-19 03:40:36

标签: teradata

我在teradata表中有一个TIMESTAMP列。我想将时间戳转换为纪元值。有人可以说明如何做到这一点。

1 个答案:

答案 0 :(得分:4)

这是我几年前写的SQL UDF。

如果您没有创建功能的访问权限,那么您可能会要求您轻拍或简单地剪切&粘贴计算。

/**********
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))
;

扭转计算:

/**********
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)
;

使用TO_TIMESTAMP(UnixTime)在TD14中更容易,但这仅限于INTEGER范围。