Skip to content

Instantly share code, notes, and snippets.

@yancya
Last active December 15, 2017 03:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yancya/cda3f27076998c961db0 to your computer and use it in GitHub Desktop.
Save yancya/cda3f27076998c961db0 to your computer and use it in GitHub Desktop.
date_trunc alternative of BigQuery
select timestamp(regexp_replace(string(ts), r'^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}).*', '\\1')) as date_trunc_second,
timestamp(regexp_replace(string(ts), r'^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:).*', '\\100')) as date_trunc_minute,
timestamp(regexp_replace(string(ts), r'^(\d{4}-\d{2}-\d{2} \d{2}:).*', '\\100:00')) as date_trunc_hour,
timestamp(regexp_replace(string(ts), r'^(\d{4}-\d{2}-\d{2}).*', '\\1 00:00:00')) as date_trunc_day,
timestamp(regexp_replace(string(ts), r'^(\d{4}-\d{2}).*', '\\1-01 00:00')) as date_trunc_month,
timestamp(regexp_replace(string(ts), r'^(\d{4}).*', '\\1-01-01 00:00')) as date_trunc_year,
timestamp(regexp_replace(string(ts), r'^(\d{3}).*', '\\10-01-01 00:00')) as date_trunc_decade,
timestamp(regexp_replace(string(ts), r'^(\d{2}).*', '\\100-01-01 00:00')) as date_trunc_century,
timestamp(regexp_replace(string(ts), r'^(\d{1}).*', '\\1000-01-01 00:00')) as date_trunc_millennium
from (select cast('2014-08-19 12:41:35.220000' as timestamp) as ts) as t
Row date_trunc_second date_trunc_minute date_trunc_hour date_trunc_day date_trunc_month date_trunc_year date_trunc_decade date_trunc_century date_trunc_millennium
1 2014-08-19 12:41:35 UTC 2014-08-19 12:41:00 UTC 2014-08-19 12:00:00 UTC 2014-08-19 00:00:00 UTC 2014-08-01 00:00:00 UTC 2014-01-01 00:00:00 UTC 2010-01-01 00:00:00 UTC 2000-01-01 00:00:00 UTC 2000-01-01 00:00:00 UTC
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment