Updated on 2026-11-06 GMT+08:00

datetrunc

The datetrunc function is used to calculate the date value obtained by truncating the date according to the time unit specified by datepart.

The portion before the datepart is truncated, and the truncated portion is automatically filled with default values. For details, see Example Code.

Syntax

datetrunc (string date, string datepart)

Parameters

Table 1 Parameter descriptions

Parameter

Mandatory

Type

Description

date

Yes

DATE

or

STRING

The start date.

Formats:

  • yyyy-mm-dd
  • yyyy-mm-dd hh:mi:ss
  • yyyy-mm-dd hh:mi:ss.ff3

datepart

Yes

STRING

The time unit to return.

The datepart parameter supports extended date formats: year, month or mon, day, and hour.

  • yyyy indicates year.
  • mm indicates month.
  • dd indicates day.
  • hh indicates hour.
  • mi indicates minute.
  • ss indicates second.

Return Values

Returns a date value of type DATE or STRING.

  • If date is not of type DATE or STRING, an error is returned with the message "data type mismatch".
  • If date is of type DATE or STRING but does not conform to the input format for date values, NULL is returned.
  • If the datepart value is NULL, NULL is returned.
  • Truncation is performed according to the specified time unit (e.g., hh truncates by hour).

Example Code

Example static data

  • Example 1:
    select datetrunc('2023-08-14 17:00:00', 'yyyy');

    Returns 2023-01-01 00:00:00.

  • Example 2:
    select datetrunc('2023-08-14 17:00:00', 'month');

    Returns 2023-08-01 00:00:00.

  • Example 3:
    select datetrunc('2023-08-14 17:00:00', 'DD');

    Returns 2023-08-14 00:00:00.

  • Example 4:
    select datetrunc('2023-08-14', 'yyyy');

    Returns 2023-01-01.

  • Example 5:
    select datetrunc('2023-08-14 17:11:11', 'hh');

    Returns 2023-08-14 17:00:00.

  • Example 6:
    select datetrunc('2023-08-14', null);

    Returns NULL.