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

This generates a type error.

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.

Use the datetime.timedelta class:

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

Your example could be written as:

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


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

Compare the difference to a timedelta that you create:

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


if (datetime.now() - self.timestamp).total_seconds() > 100:

Assuming self.timestamp is an datetime instance

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:

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

Like so:

# self.timestamp should be a datetime object
if (datetime.now() - self.timestamp).seconds > 100:
    print "object is over 100 seconds old"

Convert your time delta into seconds and then use conversion back to hours elapsed and remaining minutes.



 seconds_in_day = 24 * 60 * 60
 seconds_in_hour= 1 * 60 * 60

 elapsed_seconds=delta.days * seconds_in_day + delta.seconds

 hours=  int(elapsed_seconds/seconds_in_hour)
 minutes= int((elapsed_seconds - (hours*seconds_in_hour))/60)

 print("Hours {} Minutes {}".format(hours,minutes))