deemel
deemel

Reputation: 1036

epoch conversion in python

While processing logfiles, I need to compare epoc and human-readable timestamps.

epoc=time.strftime("%d.%m.%Y %H:%M - %Z", time.localtime(1358252743927))
print epoc

and

t1=time.gmtime(1358252743927)
print t1

both return something like

26.04.45011 22:52 - CEST

Whereas converting 1358252743927 using this site returns

GMT: Tue, 15 Jan 2013 12:25:43 GMT
Your time zone: 1/15/2013 1:25:43 PM GMT+1

Which is the correct time - but somehow python can't handle this timestamp.

Does anyone have an idea how to convert the timestamp to get the latter result?

Upvotes: 1

Views: 1723

Answers (2)

kratenko
kratenko

Reputation: 7592

Looks like that timestamp you have there has milliseconds with it, the gmtitme function cannot handle that. The site you mentioned can. If you remove the last three digits on that huge number, the site will still give you the same result, as it does not believe, that you really want the year 45011.

So just divide the number by 1000 before passing it (if you are sure, you always get that high resolution), and you are fine:

t1 = time.gmtime(1358252743.927)
print t1

gives:

time.struct_time(tm_year=2013, tm_mon=1, tm_mday=15, tm_hour=12, tm_min=25, tm_sec=43, tm_wday=1, tm_yday=15, tm_isdst=0)

which seems fine.

Upvotes: 3

Jonathan Ballet
Jonathan Ballet

Reputation: 1003

Python handles epoch time in seconds, and I suspect, looking how big is your timestamp, that is is in milliseconds instead.

If you drop the last 3 digits, you will get the expected time:

>>> value = 1358252743927
>>> import time
>>> time.strftime("%d.%m.%Y %H:%M - %Z", time.localtime(value / 1000))
'15.01.2013 13:25 - CET'

(minus the timezone issues known with Python).

Upvotes: 2

Related Questions