Would anyone have a better way to make a count down timer for a specific date and time in UTC time zone with the datetime
library?
The script below works to count down to the start_time
but I have something wrong in the while loop there is an if statement where I am trying to print every minute the duration remaining time left in minutes until the countdown ends, but the %
is not working the way I thought it would, its just prints every millisecond or second the remaining. Any tips greatly appreciated on to write this better?...
from datetime import datetime,timezone
start_script = datetime(2022, 7, 9, 13, 50, tzinfo=timezone.utc)
def timer():
while (start_script - datetime.now(timezone.utc)).total_seconds() >= 0:
if (60 - (start_script - datetime.now(timezone.utc)).total_seconds() % 60):
print("RUNNING IN MINUTES: ",((start_script - datetime.now(timezone.utc)).total_seconds() /60))
timer()
print("RUN MY SCRIPT NOW!!!")
CodePudding user response:
You can use this:
from datetime import datetime
def timer(countdown_to):
last_minute = datetime.now().minute
while datetime.now() <= countdown_to:
if datetime.now().minute != last_minute:
print('Time left:', int((countdown_to - datetime.now()).total_seconds() // 60), 'min')
print('Time now:', datetime.now(), '\n') # Just for testing, you can remove if you want
last_minute = datetime.now().minute
timer(datetime(2022, 7, 9, 14, 22))
I started running at 14:16:25, this is the output I got:
Time left: 5 min
Time now: 2022-07-09 14:17:00.000087
Time left: 4 min
Time now: 2022-07-09 14:18:00.000073
Time left: 3 min
Time now: 2022-07-09 14:19:00.000158
Time left: 2 min
Time now: 2022-07-09 14:20:00.000077
Time left: 1 min
Time now: 2022-07-09 14:21:00.000070
Time left: 0 min
Time now: 2022-07-09 14:22:00.000326