1 回答

TA貢獻1821條經驗 獲得超6個贊
您可以使用它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"])
添加回答
舉報