A quick question to Bigquery gurus.
Here are two methods for extracting date from a timestamp in Bigquery using standardSQL
#standardSQL
#1
DATE(TIMESTAMP_MILLIS(CAST((timestamp) AS INT64)))
#2
EXTRACT(DATE FROM TIMESTAMP_MILLIS(timestamp))
Which one is more preferable and why? Thanks!
date_expression [, timezone]: It converts a DATE object to a TIMESTAMP data type. datetime_expression [, timezone]: It converts a DATETIME object to a TIMESTAMP data type. This BigQuery Timestamp function supports an optional parameter to specify a time zone. If no time zone is specified, the default time zone, UTC, is used.
The format is: YYYY-MM-DD [Timezone] HH:MM:SS (e.g. 2021-05-15 16:45:18 UTC). The Timestamp functions return a timestamp from a value or a pair of values. Google BigQuery supports the following BigQuery Timestamp functions.
DATE, TIME, DATETIME, and TIMESTAMP are the four groups of date and time functions that are supported in BigQuery. These groups contain more specific functions such as CURRENT_DATETIME, DATE_SUB, EXTRACT, FORMAT_TIME, and so on.
To get the current date or time expression you can use the CURRENT function in BigQuery. The following statements show the syntax in which the function can be written: The example below shows how to use the CURRENT_DATETIME function to get today’s date and current time.
It really comes down to personal preference; one isn't superior to the other since they have the same semantics and performance. The argument in favor of using EXTRACT
is that if you are extracting other date/time parts in the select list, it mirrors them. For example:
SELECT
EXTRACT(DATE FROM TIMESTAMP_MILLIS(timestamp)) AS date,
EXTRACT(ISOYEAR FROM TIMESTAMP_MILLIS(timestamp)) AS iso_year,
EXTRACT(ISOWEEK FROM TIMESTAMP_MILLIS(timestamp)) AS iso_week
FROM YourTable;
Compared to:
SELECT
DATE(TIMESTAMP_MILLIS(timestamp)) AS date,
EXTRACT(ISOYEAR FROM TIMESTAMP_MILLIS(timestamp)) AS iso_year,
EXTRACT(ISOWEEK FROM TIMESTAMP_MILLIS(timestamp)) AS iso_week
FROM YourTable;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With