compare datetime.now() with utc timestamp with python 2.7
<p>I have a timestamp such <code>1474398821633L</code> that I think is in utc. I want to compare it to datetime.datetime.now() to verify if it is expired.</p>

<p>I am using python 2.7</p>

<pre><code>from datetime import datetime

timestamp = 1474398821633L
now = datetime.now()

if datetime.utcfromtimestamp(timestamp) &lt; now:
    print "timestamp expired"
</code></pre>

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

<p>What can I do?</p>

<p>As <a href="http://stackoverflow.com/a/39602250/4279">@mgilson pointed out</a> your input is likely "milliseconds", not "seconds since epoch".</p>

<p>Use <code>time.time()</code> instead of <code>datetime.now()</code>:</p>

<pre><code>import time

if time.time() &gt; (timestamp_in_millis * 1e-3):
    print("expired")
</code></pre>

<p>If you need <code>datetime</code> then use <code>datetime.utcnow()</code> instead of <code>datetime.now()</code>. Do not compare <code>.now()</code> that returns local time as a naive datetime object with <code>utcfromtimestamp()</code> 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).</p>

<pre><code>from datetime import datetime

now = datetime.utcnow()
then = datetime.utcfromtimestamp(timestamp_in_millis * 1e-3)
if now &gt; then:
    print("expired")
</code></pre>

<p>See more details in <a href="http://stackoverflow.com/q/26313520/4279">Find if 24 hrs have passed between datetimes - Python</a>.</p>

python python-2.7