Below the Radar Below the Radar - 2 months ago 18
Python Question

compare datetime.now() with utc timestamp with python 2.7

I have a timestamp such

1474398821633L
that I think is in utc. I want to compare it to datetime.datetime.now() to verify if it is expired.

I am using python 2.7

from datetime import datetime

timestamp = 1474398821633L
now = datetime.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

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 datetime.now() to make sure that you're handling timezones correctly :-).