You can use datetime
to perform the necessary calculations.
In this example, the target time is parsed using strptime
but the date is not supplied so the time part is correct but the date part is wrong. The first three fields (year, month, day) are then replaced with today’s date to produce a datetime object that correctly represents the target time. The current time can then be subtracted to give a timedelta
object that represents the amount of time that needs to be waited until the task can be run.
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"])
solved How to take time as a input from user in the form HHMM and then run a function at that time