BigQuery: convert epoch to TIMESTAMP

末鹿安然 提交于 2020-12-29 05:34:48

问题


I'm trying to range-join two tables, like so

SELECT *
FROM main_table h
INNER JOIN
    test.delay_pairs d
ON
    d.interval_start_time_utc < h.visitStartTime
    AND h.visitStartTime < d.interval_end_time_utc

where h.visitStartTime is an INT64 epoch and d.interval_start_time_utc and d.interval_end_time_utc are proper TIMESTAMPs.

The above fails with

No matching signature for operator < for argument types: TIMESTAMP, INT64. Supported signature: ANY < ANY

Neither wrapping h.visitStartTime in TIMESTAMP() nor CAST(d.interval_start_time_utc AS INT64) work. How do I make the two comparable in BigQuery's Standard SQL dialect?


回答1:


You can use timestamp conversion functions like TIMESTAMP_SECONDS, TIMESTAMP_MILLIS, TIMESTAMP_MICROS

for example, assuming your h.visitStartTime is microseconds since the unix epoch

SELECT *
FROM main_table h
INNER JOIN test.delay_pairs d
ON d.interval_start_time_utc < TIMESTAMP_MICROS(h.visitStartTime)
AND TIMESTAMP_MICROS(h.visitStartTime) < d.interval_end_time_utc  



回答2:


With standard sql you can use one of those, depending on precision:

  • DATE_FROM_UNIX_DATE - from days epoch to date
  • TIMESTAMP_SECONDS - from seconds epoch to timestamp
  • TIMESTAMP_MILLIS - from milliseconds epoch to timestamp
  • TIMESTAMP_MICROS - from microseconds epoch to timestamp

See documentation here: https://cloud.google.com/bigquery/docs/reference/standard-sql/functions-and-operators#timestamp_seconds

With legacy sql you can just use TIMESTAMP function and multiply or divide by 1000 to bring it to needed epoch type:

SELECT 
  TIMESTAMP(epoch_in_millis / 1000) AS datetime
FROM 
  my_table


来源:https://stackoverflow.com/questions/37861500/bigquery-convert-epoch-to-timestamp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!