如何检查两个日期之间的差异(以秒为单位)?

时间:2010-12-06 01:28:43

标签: python time datediff

必须有一种更简单的方法来做到这一点。我有想要每隔一段时间刷新一次的对象,所以我想记录它们的创建时间,检查当前的时间戳,并根据需要进行刷新。

datetime.datetime已被证明是困难的,我不想深入了解ctime库。这种事情有什么比较容易的吗?

7 个答案:

答案 0 :(得分:406)

如果您想计算两个已知日期之间的差异,请使用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

答案 1 :(得分:28)

import time  
current = time.time()

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

那对你有用吗?

答案 2 :(得分:15)

>>> 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

答案 3 :(得分: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)

答案 4 :(得分:0)

这是为我工作的人。

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;

希望这会有所帮助!

答案 5 :(得分:0)

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

end_time.timestamp() - start_time.timestamp()

答案 6 :(得分: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())