SELECT knowledge FROM sql_resources WHERE category='bigquery-standard-sql' AND slug='datetime-diff'
DATETIME_DIFF
You might also want to see DATE_DIFF, TIMESTAMP_DIFF, OR TIME_DIFF
Definition
The DATETIME_DIFF function in BigQuery allows you to find the difference between 2 DATETIMEs in the specified date_part interval.
Where date_part can be any of the following: 
DATETIME_DIFF(datetime_expression_a, datetime_expression_b, date_part)- MICROSECOND
- MILLISECOND
- WEEK: Begins on Sunday
- WEEK(): Begins on where WEEKDAY can be SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY.
- ISOWEEK: Uses ISO 8601 week boundaries. ISO weeks begin on Monday.
- ISOYEAR: Uses the 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: INT64
| minutes_difference | quarter_difference | 
|---|---|
| 99 | 3 | 
Practical Info
- If the first DATETIMEis earlier than the second one then the output will be negative
- Throws an error if the computation overflows the result type, such as if the difference in microseconds between the two DATETIMEobjects would overflow anINT64value.
Common Questions
How to filter for the last n days?
A common SQL query WHERE clause is to just pull the data for the last n days. In this case, we can make use of DATETIME_DIFF and CURRENT_DATETIME: 
Loading code...
| date | days_since | 
|---|---|
| 2021-01-22T00:00:00 | 21 | 
| 2021-01-26T00:00:00 | 17 | 
Troubleshooting Common Errors
Argument 2 of DATETIME_DIFF has incorrect type: expected datetime found date.
This one is all too common. If you're using DATETIME_DIFF, you'll need to make sure both of your datetimes are indeed DATETIME data types, and not DATEs or TIMESTAMPs. It's usually easy enough to add a CAST(datetime_col as DATETIME) to your function: 
Loading code...
Related Pages
- TIMESTAMP_DIFF
- Dates & Times in Standard SQL
Loading code...