Below the Radar Below the Radar - 1 year ago 131
Python Question

compare with utc timestamp with python 2.7

I have a timestamp such

that I think is in utc. I want to compare it to to verify if it is expired.

I am using python 2.7

from datetime import datetime

timestamp = 1474398821633L
now =

if datetime.utcfromtimestamp(timestamp) < now:
print "timestamp expired"

However I got this error when trying to create a datetime object from the timestamp:
ValueError: timestamp out of range for platform localtime()/gmtime() function

What can I do?

Answer Source

It looks like your timestamp is in milliseconds. Python uses timestamps in seconds:

>>> datetime.datetime.utcfromtimestamp(1474398821.633)
datetime.datetime(2016, 9, 20, 19, 13, 41, 633000)

In other words, you might need to divide your timestamp by 1000. in order to get it in the proper range.

Also, you'll probably want to compare datetime.utcnow() instead of to make sure that you're handling timezones correctly :-).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download