SELECT knowledge FROM sql_resources WHERE category='bigquery-standard-sql' AND slug='time-diff'
TIME_DIFF
See also DATE_DIFF, DATETIME_DIFF, or TIMESTAMP_DIFF
Definition
The TIME_DIFF function allows you to find the difference between 2 TIMEs in the specified part interval.
Where part can be any of the following:
TIME_DIFF(time_expression_a, time_expression_b, part)MICROSECONDMILLISECOND
Returns: INT64
| first_time | second_time | difference |
|---|---|---|
| 15:30:00 | 14:35:00 | 55 |
Practical Info
- If the first
TIMEis 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
TIMEobjects would overflow anINT64value.
Common Questions
How to filter for the last n seconds?
A common SQL query WHERE clause is to just pull the data for the last n seconds. In this case, we can make use of TIME_DIFF and CURRENT_TIME:
Loading code...
| time | seconds_since |
|---|---|
| 13:05:00 | -2336 |
| 13:05:00 | -2336 |
| 13:05:00 | -2336 |
Troubleshooting Common Errors
Argument 2 of TIME_DIFF has incorrect type: expected time found datetime.
This one is all too common. If you're using TIME, you'll need to make sure both of your TIMEs are indeed TIME data types, and not DATEs or DATETIMEs. It's usually easy enough to add a CAST(timestamp_col as TIME) to your function:
Loading code...
Related Pages
- DATETIME_DIFF
- Dates & Times in Standard SQL
Loading code...