← Back to SQL, page 9

sql-0163 · Easy fresher

Convert the Unix timestamp 1772359200 to a readable date and time, and convert a date back to Unix seconds.

In SQLite use datetime(1772359200, 'unixepoch') and strftime('%s', '2026-03-01 10:00:00'), or unixepoch() in 3.38+. In PostgreSQL use to_timestamp(1772359200) and EXTRACT(EPOCH FROM ts). Unix time is in UTC, so the readable value is UTC unless converted.

Full answer
sql
SELECT datetime(1772359200, 'unixepoch') AS readable,
       unixepoch('2026-03-01 10:00:00') AS back_to_unix,
       typeof(strftime('%s', '2026-03-01 10:00:00')) AS strftime_type;
readableback_to_unixstrftime_type
2026-03-01 10:00:001772359200text

The 'unixepoch' modifier tells SQLite to read the number as seconds since 1970-01-01 UTC. Without it, the number would be read as a Julian day. unixepoch() returns an integer, while strftime('%s') returns text.

PostgreSQL:

sql
SET TIME ZONE 'UTC';
SELECT to_timestamp(1772359200) AS readable,
       EXTRACT(EPOCH FROM TIMESTAMPTZ '2026-03-01 10:00:00+00')::bigint AS back_to_unix;
readableback_to_unix
2026-03-01 10:00:00+00:001772359200

Some systems store milliseconds. Divide by 1000 first, or the result lands tens of thousands of years in the future.

sql
SELECT datetime(1772359200, 'unixepoch') AS readable,
       unixepoch('2026-03-01 10:00:00') AS back_to_unix,
       typeof(strftime('%s', '2026-03-01 10:00:00')) AS strftime_type;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • SQLite: datetime(n, 'unixepoch') and unixepoch()
  • PostgreSQL: to_timestamp(n) and EXTRACT(EPOCH FROM ...)
  • Unix time counts seconds from 1970 in UTC
  • Check for millisecond values

Common mistakes

  • Forgetting the 'unixepoch' modifier
  • Treating millisecond timestamps as seconds

Follow-ups

  • How would you store event times compactly?
  • How would you show the time in a user's zone?

Tips

  • Mention the milliseconds trap