比较 Python 中的时间增量

我有一个变量,它是 <type 'datetime.timedelta'>,我想比较它与某些值。

假设 d 产生这个 datetime.timedelta0:00:01.782000

我想这样比较:

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

我已经尝试转换 datetime.timedelta.strptime(),但似乎确实工作。有没有更简单的方法来比较这个值?

131139 次浏览

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

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

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:
if d.total_seconds() > 60:
print("elapsed time is greater than 1 minute")

but it requires python 2.7+