// dates & times reference

SQL DATETIMEFROMPARTS function

Returns a date plus time from year, month, day, hour, minute, seconds and milliseconds. SQL Server's DATETIMEFROMPARTS takes all seven and returns datetime.

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

Синтаксис

DATETIMEFROMPARTS(y, m, d, hh, mi, ss, ms)  -- SQL Server
MAKE_TIMESTAMP(y, m, d, hh, mi, ss)  -- PostgreSQL

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

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

ДвижокSupportЗаметки
SQL Server Да Supported under this name.
PostgreSQL Different name or syntax make_timestamp()
MySQL Different name or syntax TIMESTAMP(date, MAKETIME(hh, mi, ss)), or STR_TO_DATE
SQLite Different name or syntax printf a string into datetime()
Oracle Different name or syntax TO_DATE of a composed string

Примеры

SQL Server

SELECT DATETIMEFROMPARTS(2024, 1, 15, 9, 30, 0, 0) AS meeting;

PostgreSQL

SELECT make_timestamp(2024, 1, 15, 9, 30, 0) AS meeting;

SQLite

SELECT datetime(printf('%04d-%02d-%02d %02d:%02d:%02d', 2024, 1, 15, 9, 30, 0)) AS meeting;

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

  • The seventh argument is milliseconds (500 is half a second), and the datetime result still rounds to .000, .003 or .007. DATETIME2FROMPARTS gives exact fractions.
  • make_timestamp takes seconds as a double, so 59.5 is valid there; SQL Server keeps fractions in the separate seventh argument instead.
  • SQL Server and PostgreSQL error on out-of-range parts, but the string-building routes do not: SQLite turns hour 25 into NULL and day 30 of February into March 1.

Questions about DATETIMEFROMPARTS

Why seven arguments on SQL Server but six on PostgreSQL?

SQL Server's seventh is milliseconds. PostgreSQL folds fractions into its double-precision seconds argument.

Is there DATETIME2FROMPARTS?

Yes. It takes eight arguments: the seventh is the fraction and the eighth its number of digits, so DATETIME2FROMPARTS(2024, 1, 15, 9, 30, 0, 5, 1) is 09:30:00.5.

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

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// 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.