python - 如何以 HHMM 形式将时间作为用户的输入,然后在那时运行一个函数
问题描述
我正在编写一个代码,其中将使用循环多次以 HHMM 的形式向用户询问时间,然后将这个时间附加到一个列表中。现在我希望在用户提供的列表中的不同时间执行一个函数。
解决方案
您可以使用它datetime
来执行必要的计算。
在此示例中,使用解析目标时间strptime
但未提供日期,因此时间部分正确但日期部分错误。然后将前三个字段(年、月、日)替换为今天的日期,以生成正确表示目标时间的日期时间对象。然后可以减去当前时间,得到一个timedelta
对象,该对象表示在可以运行任务之前需要等待的时间量。
import time
import datetime
def 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"])
推荐阅读
- google-chrome - 发送有关所有选项卡的信息,但侦听器仅工作一次并显示最终选项卡的 URL
- javascript - React Calculator:输入标签值显示小数和其他符号不正确
- html - 如何在 Chrome 中将表情符号在视觉上水平居中?
- javascript - D3 平分线功能无法正常工作
- c++ - c++ 中的这种语法是什么意思?
- python - 熊猫大步阅读 csv
- html - 如何下载和显示pdf
- javascript - 如何在 ng datepicker 中设置语言环境
- javascript - 如何在 JavaScript 中的窗口上调度 mousedown/click 事件?
- ios - 如何使用自定义操作删除部分中的单元格?