Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...