You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让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_times set: 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 20:57:50