PostgreSQL Error – Timestamp Out of Range Converting Epoch

postgresqlpostgresql-10timestamptype conversion

I'm getting ERROR: timestamp out of range: "1.52701e+15" when trying to convert an epoch stored as a bigint into a timestamp (value is taken from a real database table):

select to_timestamp(1527012834506374);
ERROR:  timestamp out of range: "1.52701e+15"

Other approaches to conversion don't work either:

select 1527012834506374::abstime::timestamp;
ERROR:  cannot cast type bigint to abstime

select 1527012834506374::integer::abstime::timestamp;
ERROR:  integer out of range

It's a valid epoch; https://www.epochconverter.com/ tells me 1527012834506374 is equivalent to 2018-05-22 06:13:54.506 UTC

How can I do the conversion using SQL in Postgres?

Best Answer

When I paste the value 1527012834506374 into https://www.epochconverter.com/ I see the warning:

Assuming that this timestamp is in microseconds (1/1,000,000 second):

Postgres' to_timestamp() assumes an epoch with seconds, not microseconds, so you need to use:

select to_timestamp(1527012834506374 / 1000000.0)