用python比较一天中的时间

2024-09-26 22:52:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我的脑袋被Python时间弄得有点乱。你知道吗

快速总结:我的应用程序应该从配置中读取一些时间(格式示例:“23:03”),然后while循环将当前时间与配置时间进行比较,如果一天中的分钟数匹配,则执行某些操作。你知道吗

我的问题是,当我编写if语句时,时间格式略有不同,当时间匹配时,它不会返回true。你知道吗

while True:
    currentTime = datetime.datetime.now()
    morningTime = datetime.datetime(*time.strptime(config.get('general','morningTime'), "%H:%M")[:6])

    if (currentTime.time() == morningTime.time()):
        #do stuff! times match

    pprint (currentTime.time())
    pprint (morningTime.time())

这将返回:

datetime.time(23, 3, 6, 42978)
datetime.time(23, 3)

我不想要一个特别想要的精确匹配在任何小于一分钟,所以我应该如何比较时间?你知道吗


Tags: true应用程序示例datetimeiftime格式时间
2条回答

您可以放弃从^{} object检索到的秒和微秒,如下所示:

now = currentTime.time().replace(second=0, microsecond=0)
pprint(now) # should print something like datetime.time(23, 3)

然后将时间与==进行比较,得到只精确到一分钟的时间匹配。你知道吗

我强烈建议使用Arrow进行数据操作。你可以这样做:

import arrow

current_time = arrow.now()
morning_time = arrow.get(config.get('general','morningTime'), 'HH:mm')

if current_time.minute == morning_time.minute:
    certain_actions()

'HH:mm'可能因morningTime的格式而异。你知道吗

相关问题 更多 >

    热门问题