Comparing a time delta in python Comparing a time delta in python python python

Comparing a time delta in python


You'll have to create a new timedelta with the specified amount of time:

d > timedelta(minutes=1)

Or this slightly more complete script will help elaborate:

import datetimefrom time import sleepstart = datetime.datetime.now()sleep(3)stop = datetime.datetime.now()elapsed = stop - startif elapsed > datetime.timedelta(minutes=1):    print "Slept for > 1 minute"if elapsed > datetime.timedelta(seconds=1):    print "Slept for > 1 second"

Output:

Slept for > 1 second


You just need to create timedelta object from scratch, comparison after that is trivial:

>>> a = datetime.timedelta(minutes=1)>>> b = datetime.timedelta(minutes=1, seconds=1)>>> a < bTrue>>> a > bFalse


Correct me if I'm wrong but I think that you could also use the following:

Instead of

if elapsed > datetime.timedelta(seconds=1):

You could say

if elapsed.seconds > 1: