views:

4438

answers:

5

I would like to find out if a particular python datetime object is older than X hours or minutes. I am trying to do something similar to:

if (datetime.now() - self.timestamp) > 100
# Where 100 is either seconds or minutes

but this obviously gives a type error. So my question is what is the proper way to do date time comparison in python? I already looked at WorkingWithTime which is close but not exactly what I want. I assume I just want the datetime object represented in seconds so that I can do a normal int comparison. Please post lists of datetime best practices as well...

A: 

You can subtract two datetime objects to find the difference between them.
You can use datetime.fromtimestamp to parse a POSIX time stamp.

William Keller
+1  A: 

You can use a combination of the 'days' and 'seconds' attributes of the returned object to figure out the answer, like this:

def seconds_difference(stamp1, stamp2):
    delta = stamp1 - stamp2
    return 24*60*60*delta.days + delta.seconds + delta.microseconds/1000000.

Use abs() in the answer if you always want a positive number of seconds.

To discover how many seconds into the past a timestamp is, you can use it like this:

if seconds_difference(datetime.datetime.now(), timestamp) < 100:
     pass
Jerub
+2  A: 

Compare the difference to a timedelta that you create:

if datetime.datetime.now() - timestamp > datetime.timedelta(seconds = 5):
    print 'older'
William
+17  A: 

Use the datetime.timedelta class:

>>> from datetime import datetime, timedelta
>>> then = datetime.now () - timedelta (hours = 2)
>>> now = datetime.now ()
>>> (now - then) > timedelta (days = 1)
False
>>> (now - then) > timedelta (hours = 1)
True

Your example could be written as:

if (datetime.now() - self.timestamp) > timedelta (seconds = 100)

or

if (datetime.now() - self.timestamp) > timedelta (minutes = 100)
John Millikin
A: 

Like so:

# self.timestamp should be a datetime object
if (datetime.now() - self.timestamp).seconds > 100:
    print "object is over 100 seconds old"
Jeremy Cantrell
I don't think this works. The seconds attribute for a timedelta http://docs.python.org/lib/datetime-timedelta.html is limited to 1 day so if your length of time is longer than 1 day it will be inaccurate
Ryan
all that you would have to do is compare it with another timedelta instead of the seconds attribute.
Jeremy Cantrell