DATETIME_TRUNC function. Definition, syntax, examples and common errors using BigQuery Standard SQL. The DATETIME_TRUNC function in BigQuery will truncate the datetime to the given date_part.
See also DATE_TRUNC, TIMESTAMP_TRUNC, TIME_TRUNC
The DATETIME_TRUNC function in BigQuery will truncate the datetime to the given date_part.
Where date_part can be any of the following:
DATETIME_TRUNC(datetime_expression, date_part)MICROSECONDMILLISECONDWEEK(): Truncates date_expression to the preceding week boundary, where weeks begin on WEEKDAY. Valid values for WEEKDAY are SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY.ISOWEEK: Truncates date_expression to the preceding ISO 8601 week boundary. ISOWEEKs begin on Monday. The first ISOWEEK of each ISO year contains the first Thursday of the corresponding Gregorian calendar year. Any date_expression earlier than this will truncate to the preceding Monday.ISOYEAR: Truncates date_expression to the preceding ISO 8601 week-numbering year boundary. The ISO year boundary is the Monday of the first week whose Thursday belongs to the corresponding Gregorian calendar year.Returns: DATETIME
| month | minute | year |
|---|---|---|
| 2021-01-01T02:44:00 | 2021-01-01T02:44:00 | 2021-01-01T00:00:00 |
DATETIME, so even if you are truncating to the YEAR, you'll receive back the first day of that year at midnight. For that reason, it's often use in conjunction with FORMAT_DATETIME if you want to just use the year YYYY. DATETIME_TRUNC is very handy for aggregating your data by a particular date_part, like MONTH. See the example below to see how you can aggregate by MONTH:
SELECT
DATETIME_TRUNC(CAST('2021-01-01 02:44:00' AS DATETIME), MILLISECOND) AS month,
DATETIME_TRUNC(CAST('2021-01-01 02:44:00' AS DATETIME), MINUTE) AS minute,
DATETIME_TRUNC(CAST('2021-01-01 02:44:00' AS DATETIME), YEAR) AS year| total | month |
|---|---|
| 10 | 2021-02-01T00:00:00 |
| 27 | 2021-01-01T00:00:00 |
Make sure you've included your DATETIME_TRUNC column in your GROUP BY!
SELECT
SUM(number) AS total,
DATETIME_TRUNC(date, MONTH) AS month
FROM
(
SELECT
CAST('2021-02-04 12:50:01' AS DATETIME) AS date,
3 AS number
UNION ALL
( SELECT
CAST('2021-02-14 00:42:41' AS DATETIME) AS date,
7 AS number)
UNION ALL
( SELECT
CAST('2021-01-04 17:01:00' AS DATETIME) AS date,
27 AS number)
) AS table_3
GROUP BY
monthYou'll need to make sure you're using the right function for your data type. To use DATETIME_TRUNC, you must be working with a DATETIME, and not a DATE, TIMESTAMP, or TIME.
You can use CAST to change your other date types to DATETIME, or use one of the equivalent functions for other date types like DATE_TRUNC.