Type to search.

ES|QL DATE_TRUNC function

Serverless

Elastic Cloud Serverless projects are autoscaled environments, fully managed by Elastic and available on Elastic Cloud.

Availability

  • Generally available

    This functionality is generally available and ready for production usage.

Serverless interfaces and procedures might differ from classic Elastic Stack deployments.

Stack

The Elastic Stack includes Elastic's core products such as Elasticsearch, Kibana, Logstash, and Beats.

Availability

  • Generally available

    This functionality is generally available and ready for production usage.

Unless stated otherwise on the page, this functionality is available when your Elastic Stack is deployed on Elastic Cloud Hosted, Elastic Cloud Enterprise, Elastic Cloud on Kubernetes, and self-managed environments.

This documentation corresponds to the latest patch available for each minor version. If you're not using the latest patch, check the release notes for changes.

Rounds down a date to the closest interval.

Embedded
Embedded
interval
Interval; time span (DATE_PERIOD or TIME_DURATION).
date

Date expression

Rounds down a date to the closest interval since epoch, which starts at 0001-01-01T00:00:00Z.

interval date result
date_period date date
date_period date_nanos date_nanos
time_duration date date
time_duration date_nanos date_nanos
ES|QL
FROM employees
| KEEP first_name, last_name, hire_date
| EVAL year_hired = DATE_TRUNC(1 year, hire_date)
first_name:keyword last_name:keyword hire_date:date year_hired:date
Alejandro McAlpine 1991-06-26T00:00:00.000Z 1991-01-01T00:00:00.000Z
Amabile Gomatam 1992-11-18T00:00:00.000Z 1992-01-01T00:00:00.000Z
Anneke Preusig 1989-06-02T00:00:00.000Z 1989-01-01T00:00:00.000Z

Combine DATE_TRUNC with STATS to create date histograms. For example, the number of hires per year:

ES|QL
FROM employees
| EVAL year = DATE_TRUNC(1 year, hire_date)
| STATS hires = COUNT(emp_no) BY year
| SORT year
hires:long year:date
11 1985-01-01T00:00:00.000Z
11 1986-01-01T00:00:00.000Z
15 1987-01-01T00:00:00.000Z
9 1988-01-01T00:00:00.000Z
13 1989-01-01T00:00:00.000Z
12 1990-01-01T00:00:00.000Z
6 1991-01-01T00:00:00.000Z
8 1992-01-01T00:00:00.000Z
3 1993-01-01T00:00:00.000Z
4 1994-01-01T00:00:00.000Z
5 1995-01-01T00:00:00.000Z
1 1996-01-01T00:00:00.000Z
1 1997-01-01T00:00:00.000Z
1 1999-01-01T00:00:00.000Z

Or an hourly error rate:

ES|QL
FROM sample_data
| EVAL error = CASE(message LIKE "*error*", 1, 0)
| EVAL hour = DATE_TRUNC(1 hour, @timestamp)
| STATS error_rate = AVG(error) by hour
| SORT hour
error_rate:double hour:date
0.0 2023-10-23T12:00:00.000Z
0.6 2023-10-23T13:00:00.000Z