Unix timestamps in SQL

Every database can convert epoch seconds, each with its own function names. The differences that matter are which ones apply the session time zone, and what happens after 2038.

MySQL and MariaDB

SELECT UNIX_TIMESTAMP();                          -- current epoch seconds
SELECT CAST(UNIX_TIMESTAMP(NOW(3)) * 1000 AS UNSIGNED);   -- current epoch milliseconds
SELECT FROM_UNIXTIME(1700000000);                 -- 2023-11-14 22:13:20 when the session time zone is UTC
SELECT FROM_UNIXTIME(1700000000123 / 1000);       -- from milliseconds, keeps the fraction
SELECT UNIX_TIMESTAMP('2023-11-14 22:13:20');     -- 1700000000 when the session time zone is UTC
SET time_zone = '+00:00';                         -- make both functions work in UTC for this session

Both functions convert through the session time_zone, so the same query gives different answers on differently configured servers. The TIMESTAMP column type is stored as 32-bit epoch seconds and ends at 2038-01-19 03:14:07 UTC; DATETIME does not have that limit. FROM_UNIXTIME returns NULL for negative values.

PostgreSQL

SELECT extract(epoch FROM now())::bigint;                                    -- current epoch seconds
SELECT (extract(epoch FROM now()) * 1000)::bigint;                           -- milliseconds
SELECT to_timestamp(1700000000);                                             -- timestamptz, shown in the session TimeZone
SELECT to_timestamp(1700000000) AT TIME ZONE 'UTC';                          -- 2023-11-14 22:13:20
SELECT to_timestamp(1700000000123 / 1000.0);                                 -- from milliseconds
SELECT extract(epoch FROM timestamptz '2023-11-14 22:13:20+00')::bigint;     -- 1700000000

to_timestamp returns timestamp with time zone, which is an instant; only its display follows the session TimeZone. Taking extract(epoch …) from a timestamp without time zone does no zone conversion at all: it counts seconds from 1970-01-01 00:00 as if the value were UTC. Negative timestamps work.

SQLite

SELECT unixepoch();                                              -- → e.g. 1763164800   SQLite 3.38 and later
SELECT CAST(strftime('%s', 'now') AS INTEGER);                   -- → e.g. 1763164800   any version
SELECT datetime(1700000000, 'unixepoch');                        -- → 2023-11-14 22:13:20
SELECT strftime('%Y-%m-%dT%H:%M:%SZ', 1700000000, 'unixepoch');  -- → 2023-11-14T22:13:20Z
SELECT datetime(1700000000123 / 1000, 'unixepoch');              -- → 2023-11-14 22:13:20   from milliseconds
SELECT unixepoch('2023-11-14 22:13:20');                         -- → 1700000000
SELECT CAST(strftime('%s', '2023-11-14T22:13:20Z') AS INTEGER);  -- → 1700000000
SELECT unixepoch('2023-11-14 17:13:20-05:00');                   -- → 1700000000

SQLite has no date type: it stores text, real or integer and the date functions interpret them. They work in UTC unless you add the 'localtime' modifier. unixepoch() needs SQLite 3.38 (2022) or later; strftime('%s', …) works on any version but returns text, hence the CAST.

SQL Server

SELECT DATEDIFF_BIG(SECOND, '1970-01-01', SYSUTCDATETIME());         -- current epoch seconds
SELECT DATEDIFF_BIG(MILLISECOND, '1970-01-01', SYSUTCDATETIME());    -- milliseconds
SELECT DATEADD(SECOND, 1700000000, '1970-01-01');                    -- 2023-11-14 22:13:20.000
SELECT DATEDIFF_BIG(SECOND, '1970-01-01', '2023-11-14T22:13:20');    -- 1700000000

-- from milliseconds: DATEADD takes an int, so split the value
DECLARE @ms bigint = 1700000000123;
SELECT DATEADD(MILLISECOND, @ms % 1000, DATEADD(SECOND, @ms / 1000, CAST('1970-01-01' AS datetime2(3))));

Use DATEDIFF_BIG (SQL Server 2016 and later): plain DATEDIFF returns an int and raises an overflow error for second counts past 2,147,483,647, which is the 2038 limit. The number argument of DATEADD is also an int. Use SYSUTCDATETIME() or GETUTCDATE(), not GETDATE(), which is server local time.

Storing timestamps: integer or date type?

  • A native type (timestamptz, DATETIME, datetime2) gives you date functions, readable query results and range checks. Prefer it for application data.
  • A BIGINT of epoch seconds or milliseconds is portable, compact and unambiguous about zone. It suits event logs and data exchanged with other systems. Name the column for its unit, such as created_at_ms.
  • Never use a 32-bit INT for new timestamp columns: it runs out in 2038.

Questions

Why does FROM_UNIXTIME() give a different time on another server?

It converts to the session time zone. Run SET time_zone = '+00:00' first, or compare SELECT @@session.time_zone on both servers.

How do I convert epoch milliseconds in PostgreSQL?

to_timestamp(ms / 1000.0). The division by 1000.0 rather than 1000 keeps the milliseconds.

Which column type should store a Unix timestamp?

BIGINT. A 32-bit INT overflows on 19 January 2038, and milliseconds do not fit in 32 bits at all.