select extract(epoch from my_timestamp)
This returns the time in seconds. However, this is a decimal number with fractions of the second after the decimal point. More on accuracy below.
For millions use:
select extract(epoch from my_timestamp)*1000
Test:
select my_date, extract(epoch from my_date)*interval'1s'+'epoch'::timestamp at time zone 'GMT'
Precision Note
extract returns a double precision number that corresponds to 15 digits in Postgres. This means that around 2016 (as I write this) the actual accuracy is 10 microseconds. Notice how it rounds the last digit:
select extract('epoch' from '2016-09-20T11:22:33.456789Z'::timestamp); date_part
For dates such as 270 years in the future, this data type will only be able to represent accuracy of 100 microseconds. From the point of view of 2016, it seems to be decent accuracy, and I think things can change a little before we reach this year.
select extract('epoch' from '2290-09-20T11:22:33.456789Z'::timestamp); date_part
In any case, it will continue to work fine for millisecond accuracy for a while.
source share