// dates & times reference

SQL FROM_UNIXTIME function

Converts seconds since 1970-01-01 UTC into a date-time value in the session zone. MySQL native, one idiomatic form per other engine.

Категория
Dates & times
Returns
datetime / timestamp
In this category
28 of 121

Синтаксис

FROM_UNIXTIME(1700000000)  -- MySQL
TO_TIMESTAMP(1700000000)  -- PostgreSQL
datetime(1700000000, 'unixepoch')  -- SQLite

Each block is a separate form. The support table and the examples show which engine takes which.

Поддержка движка

ДвижокSupportЗаметки
SQL Server Different name or syntax DATEADD(second, @ts, '1970-01-01'); int-only, so it overflows after 2038-01-19
PostgreSQL Different name or syntax to_timestamp(ts)
MySQL Да Supported under this name.
SQLite Different name or syntax datetime(ts, 'unixepoch')
Oracle Different name or syntax DATE '1970-01-01' + ts / 86400

Примеры

MySQL

SELECT FROM_UNIXTIME(1700000000) AS created;

PostgreSQL

SELECT to_timestamp(1700000000) AT TIME ZONE 'UTC' AS created;

SQLite

SELECT datetime(1700000000, 'unixepoch') AS created;

SQL Server

SELECT DATEADD(SECOND, 1700000000, '1970-01-01') AS created;

Полезно знать

  • SQLite needs the 'unixepoch' modifier: without it a number is read as a Julian day, and datetime(1700000000) returns NULL because that day is out of range.
  • Epoch seconds are UTC by definition; MySQL's FROM_UNIXTIME renders them in the session time_zone, so two sessions can show different wall times.
  • JavaScript-style 13-digit millisecond epochs need division: to_timestamp(ms / 1000.0), else you land tens of thousands of years out. SQL Server's DATEADD takes an int, so split large values into days and seconds.

Questions about FROM_UNIXTIME

Why is my result off by hours?

Epoch seconds are UTC. MySQL and PostgreSQL render the value in the session zone; AT TIME ZONE 'UTC' pins the display.

How do I handle millisecond epochs?

Divide by 1000 first: to_timestamp(ms / 1000.0) on PostgreSQL, FROM_UNIXTIME(ms / 1000) on MySQL. MySQL's / returns a decimal, so the milliseconds survive as a fraction.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.