Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting epoch time with milliseconds to datetime

I have used a ruby script to convert iso time stamp to epoch, the files that I am parsing has following time stamp structure:

2009-03-08T00:27:31.807 

Since I want to keep milliseconds I used following ruby code to convert it to epoch time:

irb(main):010:0> DateTime.parse('2009-03-08T00:27:31.807').strftime("%Q") => "1236472051807" 

But In python I tried following:

import time  time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807)) 

But I don't get the original time date time back,

>>> time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807)) '41152-03-29 02:50:07' >>>  

I wonder is it related to how I am formatting?

like image 276
add-semi-colons Avatar asked Feb 14 '14 19:02

add-semi-colons


People also ask

How do you convert milliseconds to epoch?

Convert from human-readable date to epochlong epoch = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse("01/01/1970 01:00:00").getTime() / 1000; Timestamp in seconds, remove '/1000' for milliseconds. date +%s -d"Jan 1, 1980 00:00:01" Replace '-d' with '-ud' to input in GMT/UTC time.

How do you convert milliseconds to date and time?

Approach : First declare variable time and store the milliseconds of current date using new date() for current date and getTime() Method for return it in milliseconds since 1 January 1970. Convert time into date object and store it into new variable date. Convert the date object's contents into a string using date.

How do I convert epoch to date?

Because our Epoch time is specified in milliseconds, we may convert it to seconds. To convert milliseconds to seconds, first, divide the millisecond count by 1000. Later, we use DATEADD() to add the number of seconds since the epoch, which is January 1, 1970 and cast the result to retrieve the date since the epoch.


2 Answers

Use datetime.datetime.fromtimestamp:

>>> import datetime >>> s = 1236472051807 / 1000.0 >>> datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f') '2009-03-08 09:27:31.807000' 

%f directive is only supported by datetime.datetime.strftime, not by time.strftime.

UPDATE Alternative using %, str.format:

>>> import time >>> s, ms = divmod(1236472051807, 1000)  # (1236472051, 807) >>> '%s.%03d' % (time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms) '2009-03-08 00:27:31.807' >>> '{}.{:03d}'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms) '2009-03-08 00:27:31.807' 
like image 185
falsetru Avatar answered Sep 19 '22 10:09

falsetru


those are miliseconds, just divide them by 1000, since gmtime expects seconds ...

time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807/1000.0)) 
like image 39
Joran Beasley Avatar answered Sep 19 '22 10:09

Joran Beasley