Question

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.

Was it helpful?

Solution

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)

OTHER TIPS

Compare the difference to a timedelta that you create:

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

Alternative:

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:
     pass

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"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top