达令说
您可以使用它datetime来执行必要的计算。在此示例中,使用解析目标时间strptime但未提供日期,因此时间部分正确但日期部分错误。然后,前三个字段(年、月、日)将替换为今天的日期,以生成正确表示目标时间的日期时间对象。然后可以减去当前时间以给出一个timedelta对象,该对象表示任务可以运行之前需要等待的时间量。import timeimport datetimedef hello(): print("hello")def run_at_times(func, times): today = datetime.date.today() for hhmm in sorted(times): dt = datetime.datetime.strptime(hhmm, "%H%M") when = datetime.datetime(*today.timetuple()[:3], *dt.timetuple()[3:6]) wait_time = (when - datetime.datetime.now()).total_seconds() if wait_time < 0: print(f'Time {when} has already passed') else: print(f'Waiting {wait_time} seconds until {when}') time.sleep(wait_time) func()run_at_times(hello, ["1041", "1203", "1420"])