用python比较一天中的时间

用python比较一天中的时间,python,Python,用python时间让我的头脑有点扭曲 快速总结:我的应用程序应该从配置中读取一些时间(格式示例:“23:03”),然后一个while循环将当前时间与配置时间进行比较,如果一天中的分钟数匹配,则执行某些操作 我的问题是,当我编写if语句时,时间格式略有不同,当时间匹配时,它不会返回true while True: currentTime = datetime.datetime.now() morningTime = datetime.datetime(*time.strptime(

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

我不希望在任何小于一分钟的时间内得到精确的匹配,因此我应该如何比较时间?

您可以放弃从以下方式检索到的秒数和微秒数:

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

然后,只需将时间与
=
进行比较,即可获得仅精确到分钟的时间匹配。

您可以放弃从类似以下的

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

然后,只需将时间与
=
进行比较,即可获得仅精确到分钟的时间匹配。

我强烈建议使用箭头进行数据操作。您可以执行以下操作:

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'
可能会因早晨时间的格式而异

我强烈建议使用箭头进行数据操作。您可以执行以下操作:

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”
的格式可能会有所不同,具体取决于
早晨时间的格式