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

发布于 2024-10-06 08:09:52 字数 140 浏览 3 评论 0原文

必须有一种更简单的方法来做到这一点。我有一些需要经常刷新的对象,因此我想记录它们的创建时间,检查当前时间戳,并根据需要刷新。

datetime.datetime 已被证明很困难,我不想深入研究 ctime 库。对于这种事情,还有什么更容易的事情吗?

There has to be an easier way to do this. I have objects that want to be refreshed every so often, so I want to record when they were created, check against the current timestamp, and refresh as necessary.

datetime.datetime has proven to be difficult, and I don't want to dive into the ctime library. Is there anything easier for this sort of thing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

时光礼记 2024-10-13 08:09:52

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

if you want to compute differences between two known dates, use total_seconds like this:

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

总攻大人 2024-10-13 08:09:52
import time  
current = time.time()

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

这对你有用吗?

import time  
current = time.time()

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

would that work for you?

时光暖心i 2024-10-13 08:09:52
>>> 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
>>> from datetime import datetime

>>>  a = datetime.now()

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

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

(7 will be whatever amount of time you waited a bit above)

I find datetime.datetime to be fairly useful, so if there's a complicated or awkward scenario that you've encountered, please let us know.

EDIT: Thanks to @WoLpH for pointing out that one is not always necessarily looking to refresh so frequently that the datetimes will be close together. By accounting for the days in the delta, you can handle longer timestamp discrepancies:

>>> 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
养猫人 2024-10-13 08:09:52

我们在 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)

We have function total_seconds() with Python 2.7
Please see below code for 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)
吃→可爱长大的 2024-10-13 08:09:52

这是为我工作的一个。

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;

希望这有帮助!

Here's the one that is working for me.

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;

Hope this helps!

醉生梦死 2024-10-13 08:09:52

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

end_time.timestamp() - start_time.timestamp()

Another approach is to use timestamp values:

end_time.timestamp() - start_time.timestamp()
谎言 2024-10-13 08:09:52

通过阅读源码,我得出一个结论:通过.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)
# !

By reading the source code, I came to a conclusion: the time difference cannot be obtained by .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 can get an accurate difference between the two times

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

in conclusion:

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

print((dt2 - dt1).total_seconds())
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文