datepart()

Extracts a specified date component from a date and returns it as an integer.

Syntax

datepart(DATE, DATEPART)

Parameters

DATE
An expression that returns a date.
DATEPART
A constant string representing the date component to extract. The supported values are as follows.
Type indicatorReturn typeDescriptionExample value
centuryintegerCentury21
dayintegerDay of month (1–31)12
decadeintegerYear divided by 10201
dowintegerDay of week, Sunday (0) through Saturday (6)1
doyintegerDay of year163
epochlongSeconds elapsed since January 1, 19701497269156
hourintegerHour of day in 24-hour format (0–23)21
isodowintegerISO 8601 day of week, Monday (1) through Sunday (7)1
isoyearintegerISO 8601 year (the year containing the first Thursday of that week)2017
microsecondsintegerSeconds and microseconds within the current minute combined (milliseconds × 1000)56371000
millenniumintegerMillennium (1000-year unit)3
millisecondsintegerSeconds and milliseconds within the current minute combined56371
min, minuteintegerMinutes (0–59)5
mon, monthintegerMonth (1–12)6
msecintegerMilliseconds within the current second (milliseconds % 1000)377
quarterintegerQuarter of the year (1–4)2
sec, secondintegerSeconds (0–59)56
timezoneintegerTime zone offset from UTC in seconds32400
timezone_hourintegerTime zone offset from UTC in hours9
timezone_minuteintegerMinutes portion of the time zone offset from UTC (excluding hours)0
weekintegerISO 8601 week number of the year24
yearintegerYear2017

Description

The datepart() function extracts the component specified by DATEPART from DATE. When epoch is specified, the function returns a 64-bit integer (long); otherwise it returns a 32-bit integer.

Returns null if DATE is null or not a timestamp type.

Error codes

90880
Raised when DATEPART is null or not a string.
90881
Raised when the DATEPART value is invalid. The type parameter contains the invalid type indicator.

Usage examples

To prepare the WEB_APACHE_SAMPLE table used in these examples, refer to Preparing sample data.

  1. Extract the hour from the access log timestamp.

    table limit=5 WEB_APACHE_SAMPLE | eval result = datepart(_time, "hour")
    | fields _time, result
    
  2. Extract the month from the access log timestamp.

    table limit=5 WEB_APACHE_SAMPLE | eval result = datepart(_time, "mon")
    | fields _time, result
    
  3. Extract the Unix epoch value from the access log timestamp.

    table limit=5 WEB_APACHE_SAMPLE | eval result = datepart(_time, "epoch")
    | fields _time, result
    
  4. NULL input

    json "{}" | eval result = datepart(null, "year")
    | # result: null
    

Compatibility

The datepart() function has been available since before Sonar 4.0.