Unix timestamps in MySQL

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

// note

FROM_UNIXTIME and UNIX_TIMESTAMP use the session time zone.

query.sql · current timestamp
SELECT UNIX_TIMESTAMP() AS unix_seconds;
SELECT UNIX_TIMESTAMP(NOW(3)) * 1000 AS unix_ms;
timestamp → date
SELECT FROM_UNIXTIME(1700000000) AS local_time;
-- convert in UTC instead:
SELECT CONVERT_TZ(FROM_UNIXTIME(1700000000), @@session.time_zone, '+00:00');
date → timestamp
SELECT UNIX_TIMESTAMP('2023-11-14 22:13:20');
// 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://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html

advertisement