What is the syntax to get the epoch from a timestamp column with time zone.
I can use with time zone
in the following way and it works as expected
select extract(epoch from timestamp with time zone '1970-01-01 00:00:00.000 +00') ;
returns 0
select extract(epoch from timestamp with time zone '1970-01-01 00:00:00.000 -0500') ;
returns 18000.000000
Great!
But this returns the same epoch for both:
select extract(epoch from ts )
from(
select to_timestamp(ts, 'yyyy-mm-dd h24:mi:ss') ts
from (
select unnest (array[
'1970-01-01 00:00:00.000 +00',
'1970-01-01 00:00:00.000 -0500'
]) ts
)
);
18000.000000
18000.000000
Where do I put the with time zone
when I am extracting the epoch for a column of timestamps?
I have tried the following with no success:
epoch from ts with time zone
–fails SQL Error [42601]: ERROR: syntax error at or near "with"epoch from ts::timestamp with time zone
— runs, but gives the same values for both
2
Answers
This might be what you’re looking for
From your query; the timezone needs to be identified through the cast first before using the epoch.
In PostgreSQL, when you convert a text timestamp to a timestamp with time zone, the conversion will use the current time zone setting unless you explicitly specify the time zone in the conversion.
However, since your timestamps already include the time zone information, you can directly cast them to
timestamptz
without usingto_timestamp
:This will correctly interpret the time zone information included in the timestamps and provide the correct epoch values.
Explanation:
The first timestamp ‘1970-01-01 00:00:00.000 +00‘ corresponds to epoch 0.
The second timestamp ‘1970-01-01 00:00:00.000 -0500‘ is 5 hours behind UTC, which corresponds to an epoch of 18000 seconds.