Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting date from timestamp in Bigquery: a preferable method

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!

like image 269
Dmitri Ilin Avatar asked Aug 29 '17 07:08

Dmitri Ilin


People also ask

What is the use of datetime_expression in BigQuery?

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.

What is the format of timestamp in BigQuery?

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.

What are the different types of date and time functions in BigQuery?

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.

How do I get the current date or time in BigQuery?

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.


Video Answer


1 Answers

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;
like image 168
Elliott Brossard Avatar answered Sep 24 '22 11:09

Elliott Brossard