Comparing a time delta in python

119,875

Solution 1

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 datetime
from time import sleep

start = datetime.datetime.now()
sleep(3)
stop = datetime.datetime.now()

elapsed = stop - start

if 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

Solution 2

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 < b
True
>>> a > b
False

Solution 3

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:

Solution 4

if d.total_seconds() > 60:
  print("elapsed time is greater than 1 minute")

but it requires python 2.7+

Share:
119,875

Related videos on Youtube

Alpesh Patel
Author by

Alpesh Patel

Updated on March 29, 2020

Comments

  • Alpesh Patel
    Alpesh Patel about 4 years

    I have a variable which is <type 'datetime.timedelta'> and I would like to compare it against certain values.

    Lets say d produces this datetime.timedelta value 0:00:01.782000

    I would like to compare it like this:

    #if d is greater than 1 minute 
    if d>1:00:
      print "elapsed time is greater than 1 minute"
    

    I have tried converting datetime.timedelta.strptime() but that does seem to work. Is there an easier way to compare this value?

    • Thomas Wouters
      Thomas Wouters about 14 years
      Note that 0:00:01.78200 is what a timedelta looks like when printed, but that's not a particularly useful format when debugging. Use repr() to show more accurate information. That way you might have guessed at the solution, as repr(d) would have shown datetime.timedelta(0, 1, 782000)
  • Fips
    Fips over 3 years
    Note if you're using Pandas there exists pandas.Timedelta with capital T...