Unix Timestamp or Epoch Timestamp to Datetime in SQL Server
Today I was working on extracting files from Amazon S3 to Azure Blob storage and I need to to refer to a control file to determine the start and end time of my extract. But unfortunately the timestamp in the control file was in Unix format.
Select lastSuccessfulWriteTimestamp from from ETL_CONTROL_TABLE
------------------------
1590796601336
------------------------
Now i need to convert this Unix Timestamp or Epoch to Datetime format so that my extract job can understand the the actual start date and end date.
Now before proceeding let me explain what's a Unix Timestamp or Epoch Timestamp?
Unix Timestamp or Epoch Timestamp is the number of "seconds" from 1st January 1970 00:00:00 hrs.
So a datetime where
Date : 1st January 1970
Time : 03 : 00 : 00 am
will be represented in Unix Timestamp or Epoch Timestamp as
3 (hours) * 60 (min) * 60 (sec) = 10,800 (this is timestamp in seconds)
3 (hours) * 60 (min) * 60 (sec) * 1000 = 1,08,00,000 (this is timestamp in milliseconds)
So the Unix time I got is in milliseconds (Since my process is in real time I need to preserve the milliseconds precisions also)
So here is the SQL logic i used in SQL server to covert this Unix Timestamp or Epoch Timestamp to Datetime.
SELECT DATEADD(MILLISECOND, CAST(RIGHT(lastSuccessfulWriteTimestamp, 3) AS INT) - DATEDIFF(MILLISECOND,GETDATE(),GETUTCDATE()), DATEADD(SECOND, CAST(LEFT(lastSuccessfulWriteTimestamp, 10) AS INT), '1970-01-01T00:00:00')) as Converted_time from
Converted_time
----------------------
2020-05-29 23:56:41.337
----------------------
In case you dont require the millisecond precision we can use the below query.
SELECT DATEADD(S, CONVERT(int,LEFT(lastSuccessfulWriteTimestamp, 10)), '1970-01-01') as Converted_time from ETL_CONTROL_TABLE
Converted_time
----------------------------
2020-05-29 23:56:41.000
----------------------------
As you can see the millisecond values are populated as 000.
Hope this was useful. Thank you
Comments
Post a Comment