如何让Python时间匹配程序持续输出字典中对应时间的结果?
Got it, let's get this sorted out for you! The problem with your current code is that once it hits a matching time, it’ll spam the same output nonstop until the minute changes—since it loops right back and checks the same time again. Also, it doesn’t track which times it’s already handled, so you might run into issues if you want the same times to trigger again later (like the next day).
Here’s a fixed version that runs continuously and triggers exactly once per matching time:
Fixed Code
import datetime import time # For the sleep delay to save CPU data = {'13:55':0,'13:56':1,'13:57':2, '13:58':3} processed_times = set() # Tracks times we've already printed for # Optional: If program starts during a matching minute, mark it as processed to avoid immediate spam initial_time = datetime.datetime.now().strftime("%H:%M") if initial_time in data: processed_times.add(initial_time) while True: current_time = datetime.datetime.now().strftime("%H:%M") # Only trigger if time is in our data AND we haven't processed it yet if current_time in data and current_time not in processed_times: print('Done') print(data[current_time]) processed_times.add(current_time) # Optional: Reset processed times at midnight if running the program overnight if datetime.datetime.now().hour == 0 and datetime.datetime.now().minute == 0: processed_times.clear() # Wait 1 second before checking again (reduces CPU usage) time.sleep(1)
Key Changes Explained:
processed_timesset: This keeps a record of every time we’ve already output the result for, so we don’t repeat the same message dozens of times in the same minute.- Dual condition check: We only print when the current time exists in your dictionary and hasn’t been processed yet.
- CPU-friendly delay: Using
time.sleep(1)stops the loop from running nonstop, which saves your computer’s resources. - Midnight reset (optional): If you run this program 24/7, uncommenting that block will clear the processed times at midnight, so the same daily times will trigger again the next day.
If you want the program to trigger every single time the minute matches (even if you restart it in the middle of that minute), just remove the initial time check block.
内容的提问来源于stack exchange,提问作者Ishaan Dugar
相关产品推荐
相关产品推荐

