Below the Radar
Below the Radar

Reputation: 7635

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?

Upvotes: 1

Views: 3048

Answers (2)

mgilson
mgilson

Reputation: 309891

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 :-).

Upvotes: 4

jfs
jfs

Reputation: 414149

As @mgilson pointed out your input is likely "milliseconds", not "seconds since epoch".

Use time.time() instead of datetime.now():

import time

if time.time() > (timestamp_in_millis * 1e-3):
    print("expired")

If you need datetime then use datetime.utcnow() instead of datetime.now(). Do not compare .now() that returns local time as a naive datetime object with utcfromtimestamp() that returns UTC time also as a naive datetime object (it is like comparing celsius and fahrenheit directly: you should convert to the same unit first).

from datetime import datetime

now = datetime.utcnow()
then = datetime.utcfromtimestamp(timestamp_in_millis * 1e-3)
if now > then:
    print("expired")

See more details in Find if 24 hrs have passed between datetimes - Python.

Upvotes: 2

Related Questions