如何使用Python的datetime模块确定当前时间是否在指定范围内?

如何使用Python的datetime模块确定当前时间是否在指定范围内?,第1张

如何使用Python的datetime模块确定当前时间是否在指定范围内

我最初的答案非常具体地针对所提出的问题,并且不适应午夜的时间范围。由于六年后这仍然是公认的答案,因此我在下面合并了@rouble的答案,该答案在我的文档中得到扩展以支持午夜。

from datetime import datetime, timedef is_time_between(begin_time, end_time, check_time=None):    # If check time is not given, default to current UTC time    check_time = check_time or datetime.utcnow().time()    if begin_time < end_time:        return check_time >= begin_time and check_time <= end_time    else: # crosses midnight        return check_time >= begin_time or check_time <= end_time# Original test case from OPis_time_between(time(10,30), time(16,30))# Test case when range crosses midnightis_time_between(time(22,0), time(4,00))

我仍然坚持下面的原始意见,即该逻辑的大多数应用程序可能更适合于

datetime
无论如何都将午夜反映为日期更改的对象。



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5630494.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存