Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an Epoch timestamp to a Date in Standard SQL

I didn't find any simple answer to this while I was looking around, so I thought I'd put it up here in case anyone was having the same problem as me with what should have been a trivial issue.

I was using ReDash analytics with Google's BigQuery and had turned on Standard SQL in the datasource settings. For the purposes of my query, I needed to convert a timestamp - unix time in milliseconds, as a string - to a Date format so that I could use the DATE_DIFF method.

As an example... "1494865480000" to "2017-05-15"

The difficulty was that casting and conversion was excessively strict and there seemed no adequate way to make it parse. See my answer down below! (Though let me know if some SQL sensei knows a more eloquent way!)

like image 710
Joseph Wolf Avatar asked May 15 '17 15:05

Joseph Wolf


People also ask

How do I convert epoch to date?

Convert from epoch to human-readable dateString date = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new java.util.Date (epoch*1000)); Epoch in seconds, remove '*1000' for milliseconds. myString := DateTimeToStr(UnixToDateTime(Epoch)); Where Epoch is a signed integer. Replace 1526357743 with epoch.

How do I change the format of a timestamp in SQL?

select to_char(sysdate, 'YYYY-MM-DD') from dual; To get this format by default, set it in your session's NLS_DATE_FORMAT parameter: alter session set NLS_DATE_FORMAT = 'YYYY-MM-DD'; You can also set the NLS_TIMESTAMP_FORMAT and NLS_TIMESTAMP_TZ_FORMAT .


2 Answers

In Standard SQL use TIMESTAMP_MICROS function together with EXTRACT(DATE FROM <timestamp>):

SELECT EXTRACT(DATE FROM TIMESTAMP_MILLIS(1494865480000))
like image 157
Mosha Pasumansky Avatar answered Sep 23 '22 11:09

Mosha Pasumansky


A simpler way with TIMESTAMP_MILLIS():

#standardSQL
SELECT DATE(TIMESTAMP_MILLIS(CAST("1494865480000" AS INT64)))

2017-05-15  
like image 42
Felipe Hoffa Avatar answered Sep 23 '22 11:09

Felipe Hoffa