Postgresql Time (epoch)

In addition to standard timestamps we can also ask postgres to return the number of seconds from the epoch.  To the uninitiated the epoch is usually the number of seconds past a fixed point in time (usually, but not always, midnight on 01/01/1970).  If you would like to know when the epoch is on your system then from a psql shell enter the following command:

postgres=# SELECT TO_TIMESTAMP(0);

my system returned 01/01/1970 as expected:

      to_timestamp
------------------------
 1970-01-01 00:00:00+00
(1 row)

If we want to return a timestamp using seconds from the epoch then we use the EXTRACT function

postgres=# SELECT EXTRACT(EPOCH FROM now());

will return something like

    date_part
------------------
 1506028038.21499
(1 row)

As with standard timestamps this is a very high resolution however thankfully we can use the same functionality to tame our return value and get the resolution that we require.

DATE_TRUNC and AT TIME ZONE work the same for epoch arguments as the do for standard timestamp examples so I am not going to go into a great deal of detail about them here, but here are a couple of examples to help you with the syntax:

postgres=# SELECT EXTRACT(EPOCH FROM DATE_TRUNC('minutes' , now()));

will return something like

 date_part
------------
 1506028320
(1 row)

Unlike a standard timestamp, when returning seconds past the epoc rather than appending the string with +XX to denote the time zone, the function will add 3600 seconds for every hour so if you are in a timezone that is GMT +6 it will add 21600 to the value when you use AT TIME ZONE

postgres=# SELECT EXTRACT(EPOCH FROM DATE_TRUNC('minutes', now() AT TIME ZONE 'Europe/London'));

if the value of now() is 1506028320 without a time zone then now() AT TIME ZONE ‘Europe/London’ will return i.e. 1506028320 + 3600

 date_part 
------------ 
1506031920
 (1 row)

One of the big advantages of using seconds from the epoch is when performing time calculations.