I have a TIMESTAMP column in a teradata table. I want to convert the timestamp to epoch value. Can someone shed some light on how to do this.
Asked
Active
Viewed 8,394 times
1 Answers
5
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.

dnoeth
- 59,503
- 4
- 39
- 56