Unix timestamps in PostgreSQL

Get the current epoch time and convert between timestamps and dates in PostgreSQL. Every snippet below is copy-ready.

// note

EXTRACT(EPOCH FROM ...) returns numeric; cast to bigint for integer seconds.

query.sql · current timestamp
SELECT EXTRACT(EPOCH FROM now())::bigint AS unix_seconds;
SELECT (EXTRACT(EPOCH FROM now()) * 1000)::bigint AS unix_ms;
timestamp → date
SELECT to_timestamp(1700000000) AT TIME ZONE 'UTC' AS utc_time;
date → timestamp
SELECT EXTRACT(EPOCH FROM TIMESTAMPTZ '2023-11-14 22:13:20+00')::bigint;
// current epoch

— seconds since 1970-01-01T00:00:00Z.

Watch out for these

  • Seconds vs milliseconds. An epoch value 13 digits long is milliseconds; 10 digits is seconds. Mixing them gives dates in 1970 or 55828.
  • Local vs UTC. Format functions that default to the machine's timezone will silently differ between servers.
  • Leap seconds. Unix time ignores them — the count is a simple 86,400 seconds per day.

Reference: https://www.postgresql.org/docs/current/functions-datetime.html

advertisement