首页 > 解决方案 > Python:如何比较两个小时

问题描述

我需要调用一个函数,确切地说是08:00, 18:00, 22:00几个小时。我创建了一个示例来测试小时之间的比较。当当前时间达到其中之一时。放入一个 While 循环,认为这个例子可以用作秒表,但我认为我错了。比较这些值的最佳方法是什么?

currentH= dt.datetime.now().strftime("%H:%M:%S")
h = "16:15:10"
while True:
    if(currentH==h):
        print 'Ok'
print 'The current Hour is: '+h

标签: python

解决方案


import datetime as dt
import time
currentH= dt.datetime.now().replace(microsecond=0).time()

hrs = ['00:02', '12:00']
for i in range(len(hrs)):
    h = [int(x) for x in hrs[i].split(':')]
    h = dt.datetime.now().replace(hour=h[0], minute=h[1], second=0,microsecond=0).time()
    hrs[i] = h

while True:
    currentH = dt.datetime.now().replace(microsecond=0).time()
    print(currentH)
    if currentH in hrs:
        print('Time is now',currentH)
    time.sleep(1)

推荐阅读