PostgreSQL: how to convert from Unix epoch to date?
152,075
Solution 1
You use to_timestamp
function and then cast the timestamp to date
select to_timestamp(epoch_column)::date;
More details:
/* Current time */
select now(); -- returns timestamp
/* Epoch from current time;
Epoch is number of seconds since 1970-01-01 00:00:00+00 */
select extract(epoch from now());
/* Get back time from epoch */
-- Option 1 - use to_timestamp function
select to_timestamp( extract(epoch from now()));
-- Option 2 - add seconds to 'epoch'
select timestamp with time zone 'epoch'
+ extract(epoch from now()) * interval '1 second';
/* Cast timestamp to date */
-- Based on Option 1
select to_timestamp(extract(epoch from now()))::date;
-- Based on Option 2
select (timestamp with time zone 'epoch'
+ extract(epoch from now()) * interval '1 second')::date;
In your case:
select to_timestamp(epoch_ms / 1000)::date;
Solution 2
select to_timestamp(cast(epoch_ms/1000 as bigint))::date
worked for me
Solution 3
On Postgres 10:
SELECT to_timestamp(CAST(epoch_ms as bigint)/1000)
Solution 4
The solution above not working for the latest version on PostgreSQL. I found this way to convert epoch time being stored in number and int column type is on PostgreSQL 13:
SELECT TIMESTAMP 'epoch' + (<table>.field::int) * INTERVAL '1 second' as started_on from <table>;
For more detail explanation, you can see here https://www.yodiw.com/convert-epoch-time-to-timestamp-in-postgresql/#more-214
Solution 5
This works for me fine:
SELECT t.*,
to_timestamp(cast(t.prev_fire_time/1000 as bigint)) as prev_fire_time,
to_timestamp(cast(t.next_fire_time/1000 as bigint)) as next_fire_time,
to_timestamp(cast(t.start_time/1000 as bigint)) as start_time
FROM public.qrtz_triggers t;
Author by
sid_com
Updated on July 24, 2021Comments
-
sid_com almost 3 years
The statement gives me the date and time.
How could I modify the statement so that it returns only the date (and not the time)?
SELECT to_timestamp( TRUNC( CAST( epoch_ms AS bigint ) / 1000 ) );
-
cryanbhu over 5 yearsdoesn't seem to work, i get syntax error. Did it change as of 2018?
-
cryanbhu over 5 yearswell i ran the
select to_timestamp(extract(epoch epoch_ms))::date;
verbatim and it gave asyntax error near epoch_ms
. I went to find other solutions and eventually this worked for meSELECT TIMESTAMP 'epoch' + (start_dt) * INTERVAL '1 second' as started_on
. Could you please explain the difference betweenTIMESTAMP
andto_timestamp()
? -
Losbaltica over 5 yearsTIMESTAMP is just column type where to_timestamp is a build in function that translates unix epoch to timestamp starting calculations from '1970-01-01 00:00:00+00'
-
a_horse_with_no_name almost 4 yearsThe above solutions will most definitely work with Postgres 12 or 13. But you can simplify your solution to
make_timestamp(sec => the_column)
-
Luc over 2 yearsany idea how to make this work for older version (Postgres 8.0 / Redshift)?