如何检查两个日期之间的秒数差异?

290

必须有更简单的方法来处理这个问题。我有一些需要定期刷新的对象,因此我想记录它们的创建时间,检查当前时间戳,并根据需要进行刷新。

datetime.datetime证明很困难,而且我不想深入研究ctime库。有没有更简单的解决方案?

7个回答

747
如果您想计算两个已知日期之间的差异,请使用total_seconds,例如:
import datetime as dt

a = dt.datetime(2013,12,30,23,59,59)
b = dt.datetime(2013,12,31,23,59,59)

(b-a).total_seconds()

86400.0

#note that seconds doesn't give you what you want:
(b-a).seconds

0


150
“注释”是人们经常忽略但非常重要的部分。我希望我能再次对它点赞。 - Dexter
有时候我注意到它给出了一个似乎不正确的结果。 59.800秒只有一瞬间的差异。 因此,对于较小的操作,如秒,毫秒或微秒的差异,可以使用(b-a).microseconds,然后除以秒(1000000)或毫秒(1000)。 - Zld Productions
@Nickpick,该值并非总是为正数。例如,以下代码输出的结果为 -60from datetime import datetime; (datetime(2019, 1, 1, 0, 0) - datetime(2019, 1, 1, 0, 1)).total_seconds() - JDiMatteo
6
这对我很有帮助。但为什么 Python 始终会给出 (b-a).seconds 的错误答案? - enchance
6
这是因为(b-a).seconds只表示时间差的秒数部分。还有(b-a).minutes、(b-a).hours等。 - Septacle
显示剩余3条评论

49
import time  
current = time.time()

...job...
end = time.time()
diff = end - current

这对你是否可行?


3
+1;我们并不关心任何一次调用的日期 - 我们关心的是经过的时间。因此,请使用原始时间戳,如所示。 - Karl Knechtel

21
>>> from datetime import datetime

>>>  a = datetime.now()

# wait a bit 
>>> b = datetime.now()

>>> d = b - a # yields a timedelta object
>>> d.seconds
7

(7将是稍微等待的时间)

我发现datetime.datetime非常有用,如果你遇到了复杂或尴尬的情况,请告诉我们。

编辑:感谢@WoLpH指出,并不总是要频繁刷新以使日期时间接近。通过考虑时间间隔中的天数,您可以处理更长的时间戳差异:

>>> a = datetime(2010, 12, 5)
>>> b = datetime(2010, 12, 7)
>>> d = b - a
>>> d.seconds
0
>>> d.days
2
>>> d.seconds + d.days * 86400
172800

1
如果你返回 d.seconds + d.days * 86400,那么对于多天来说是正确的 ;) - Wolph
9
请注意,一般情况下这是不正确的。考虑情况a - b,其中a b之前(即结果是负数):(a - b).seconds == 86282a - b == datetime.timedelta(-1, 86276, 627665)。我认为正确的方法是使用timedelta.total_seconds()...但这仅适用于py2.7+。 - David Wolever
9
确实,答案不正确,应该反映@DavidWolever的评论。正确的答案是:使用'timedelta.total_seconds()'。相应地进行了点踩操作。 - astrojuanlu
3
因为 total_seconds() 是2.7及以上版本的功能,所以感谢你回答了Python 2.6的问题并给予支持。 - Joe Holloway
@JoeHolloway我猜在Python 2.6中这个也不能正常工作。 - Vladimir Chub

12

我们在Python 2.7中拥有total_seconds()函数。 请参考以下代码,适用于Python 2.6。

import datetime
import time  

def diffdates(d1, d2):
    #Date format: %Y-%m-%d %H:%M:%S
    return (time.mktime(time.strptime(d2,"%Y-%m-%d %H:%M:%S")) -
               time.mktime(time.strptime(d1, "%Y-%m-%d %H:%M:%S")))

d1 = datetime.now()
d2 = datetime.now() + timedelta(days=1)
diff = diffdates(d1, d2)

2

另一种方法是使用时间戳值:

end_time.timestamp() - start_time.timestamp()

2
这是对我有效的一个方案。最初的回答已经起作用。
from datetime import datetime

date_format = "%H:%M:%S"

# You could also pass datetime.time object in this part and convert it to string.
time_start = str('09:00:00') 
time_end = str('18:00:00')

# Then get the difference here.    
diff = datetime.strptime(time_end, date_format) - datetime.strptime(time_start, date_format)

# Get the time in hours i.e. 9.60, 8.5
result = diff.seconds / 3600;

最初的回答

希望这能帮到你!


0
通过阅读源代码,我得出了一个结论:无法通过.seconds获取时间差。
@property
def seconds(self):
    """seconds"""
    return self._seconds

# in the `__new__`, you can find the `seconds` is modulo by the total number of seconds in a day
def __new__(cls, days=0, seconds=0, microseconds=0,
            milliseconds=0, minutes=0, hours=0, weeks=0):
    seconds += minutes*60 + hours*3600
    # ...
    if isinstance(microseconds, float):
        microseconds = round(microseconds + usdouble)
        seconds, microseconds = divmod(microseconds, 1000000)
        # ! 
        days, seconds = divmod(seconds, 24*3600)
        d += days
        s += seconds
    else:
        microseconds = int(microseconds)
        seconds, microseconds = divmod(microseconds, 1000000)
        # ! 
        days, seconds = divmod(seconds, 24*3600)
        d += days
        s += seconds
        microseconds = round(microseconds + usdouble)
    # ...

total_seconds 可以准确获取两个时间之间的差距

def total_seconds(self):
    """Total seconds in the duration."""
    return ((self.days * 86400 + self.seconds) * 10**6 +
        self.microseconds) / 10**6

总之:

from datetime import datetime
dt1 = datetime.now()
dt2 = datetime.now()

print((dt2 - dt1).total_seconds())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接