I have made a countdown timer in Python3. I have set the month to 1 and the day set to 10 just as examples. When I run it I get negative numbers because that date has already passed.
So then my question is how can I set the year to be something like 2017 so that instead of getting negative numbers I get something like 392 days.
Countdown Timer
import time
from datetime import datetime
while True:
Datetime = datetime.now()
Month = 1 - Datetime.month
Day = 10 - Datetime.day
Hour = 24 - Datetime.hour
Minute = 60 - Datetime.minute
Second = 60 - Datetime.second
Month = str(Month) + " " + "Month"
Day = str(Day) + " " + "Day"
Hour = str(Hour) + " " + "Hour"
Minute = str(Minute) + " " + "Minute"
Second = str(Second) + " " + "Second"
print(Month)
print(Day)
print(Hour)
print(Minute)
print(Second)
time.sleep(1)
You don't need to calculate by hand. Just use the capabilities of the datetime module. It offers time delta calculations:
import datetime
import time
target_date = datetime.datetime(2017, 1, 11)
timedelta_zero = datetime.timedelta(0)
while True:
diff = target_date - datetime.datetime.now()
if diff <= timedelta_zero:
break
print(diff)
time.sleep(1)
print('Takeoff!!!')
prints:
393 days, 17:09:19.278093
393 days, 17:09:18.276930
393 days, 17:09:17.274710
393 days, 17:09:16.272841
393 days, 17:09:15.270777
393 days, 17:09:14.268744
393 days, 17:09:13.267112
If you don't like the microseconds, just strip them off:
>>> print(str(diff).rsplit('.')[0])
393 days, 17:09:19
You need datetime.timedelta(0) as zero value for your time delta comparison.
For testing, set target_date to a date just a few second in the future. There should be no negative dates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With