Python 如何以HHMM的形式将时间作为用户的输入,然后在此时运行函数
我正在编写一个代码,其中用户将使用循环多次以HHMM的形式被询问时间,然后这次将被追加到列表中。现在,我希望在用户提供的列表中的不同时间执行一个函数。您可以使用Python 如何以HHMM的形式将时间作为用户的输入,然后在此时运行函数,python,datetime,time,Python,Datetime,Time,我正在编写一个代码,其中用户将使用循环多次以HHMM的形式被询问时间,然后这次将被追加到列表中。现在,我希望在用户提供的列表中的不同时间执行一个函数。您可以使用datetime执行必要的计算 在本例中,使用strtime解析目标时间,但未提供日期,因此时间部分正确,但日期部分错误。然后将前三个字段(年、月、日)替换为今天的日期,以生成正确表示目标时间的datetime对象。然后可以减去当前时间,得到一个timedelta对象,该对象表示在任务可以运行之前需要等待的时间量 import time
datetime
执行必要的计算
在本例中,使用strtime
解析目标时间,但未提供日期,因此时间部分正确,但日期部分错误。然后将前三个字段(年、月、日)替换为今天的日期,以生成正确表示目标时间的datetime对象。然后可以减去当前时间,得到一个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"])
导入时间
导入日期时间
def hello():
打印(“你好”)
def运行时间(func,时间):
今天=datetime.date.today()
对于已排序的hhmm(次):
dt=datetime.datetime.strtime(hhmm,%H%M)
when=datetime.datetime(*today.timetuple()[:3],
*dt.timetuple()[3:6])
wait_time=(when-datetime.datetime.now()).total_seconds()
如果等待时间<0:
打印(f'Time{when}已过')
其他:
打印(等待{wait_time}秒直到{when})
时间。睡眠(等待时间)
func()
在_时间运行_(您好,[“1041”、“1203”、“1420”])
相对时间还是静态时间?你的意思是什么?0001,在相对术语中,它表示函数运行1分钟后。在静态条件下,函数在00:01 A运行。时间是否总是在当天?是的,时间是在同一天