为了举例,我已经定义了一个包含特定条形码和日期时间的字典。
我想从字典中的时间中减去当前时间,但是我不知道如何为每个时间做这个。
所以我希望程序要做的是跟踪时间,当时间达到0时,超过时间,然后报警开启。但我想在字典中跟踪所有这些内容。
这是我目前的代码,现在我保持简单:
from datetime import *
import time
dict = {'619999': '2017-04-22 11:40:00', '0991626': '2017-05-20 11:40:00', '177797': '2017-06-15 11:40:00'}
def check_elapsed_time():
while True:
now = time.strftime('%Y-%m-%d %H:%M:%S')
current_time = datetime.strptime(now, '%Y-%m-%d %H:%M:%S')
component_max_time = datetime.strptime(dict['619999'], '%Y-%m-%d %H:%M:%S')
elapsed_time = component_max_time - current_time
time.sleep(1)
print(elapsed_time)
check_elapsed_time()
答案 0 :(得分:1)
您只需 遍历字典 并评估每个值。我还在你的代码中添加了一个检查,如果你的一个词典条目已经达到,就会增加一个alamr。
from datetime import *
import time
dict = {'619999': '2017-04-22 11:40:00', '0991626': '2017-05-20 11:40:00', '177797': '2017-06-15 11:40:00', '177795': '2017-03-22 14:05:00'}
def check_elapsed_time():
while True:
now = time.strftime('%Y-%m-%d %H:%M:%S')
current_time = datetime.strptime(now, '%Y-%m-%d %H:%M:%S')
for key in dict:
component_max_time = datetime.strptime(dict[key], '%Y-%m-%d %H:%M:%S')
elapsed_time = component_max_time - current_time
print(key + " " + str(elapsed_time))
if component_max_time == current_time:
print("ALARM!!!")
time.sleep(1)
check_elapsed_time()
编辑:今天为您的字典添加了一个测试用例,以便进行测试
答案 1 :(得分:1)
根据我的理解,你的算法应当在dict中的某个时间达到零时触发某些东西,即当我们的时间等于dict中的一个时间时。我建议你选择“第一次达到零”,找到最小值并单独跟踪。 你可以通过以下方式做到:
# This program works.
from datetime import *
import time
dict = {'619999': '2017-03-22 17:44:40', '0991626': '2017-05-20 11:40:00', '177797': '2017-06-15 11:40:00'}
def reaches_zero_first():
times = dict.values()
first_zero = min(times)
return first_zero
def check_elapsed_time(min_time):
while True:
now = time.strftime('%Y-%m-%d %H:%M:%S')
current_time = datetime.strptime(now, '%Y-%m-%d %H:%M:%S')
component_max_time = datetime.strptime(min_time, '%Y-%m-%d %H:%M:%S')
elapsed_time = component_max_time - current_time
time.sleep(1)
print(elapsed_time)
if(elapsed_time.total_seconds() == 0.0):
print "Reached"
break
# TRIGGER SOMETHING HERE
first_to_zero = reaches_zero_first()
check_elapsed_time(first_to_zero)