1

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?

Below the Radar
  • 7,321
  • 11
  • 63
  • 142

2 Answers2

4

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

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • 1
    @BelowtheRadar -- I guessed :-). Some other languages that I know of tend to work in milliseconds (e.g. Javascript), so it seemed natural that you could have a timestamp out of range if it was a milliseconds timestamp rather than a seconds timestamp. – mgilson Sep 20 '16 at 19:28
  • it is not enough to interpret it as milliseconds. OP should use UTC time instead of the local time returned by `datetime.now()`. – jfs Sep 20 '16 at 19:42
2

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.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670