如何以 HHMM 形式将时间作为用户的输入,然后在当时运行一个函数

我正在编写一个代码,其中将使用循环多次以 HHMM 的形式询问用户时间,然后将这次时间附加到列表中。现在我希望在用户提供的列表中的不同时间执行一个函数。



斯蒂芬大帝
浏览 114回答 1
1回答

达令说

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

相关分类

Python