Reputation: 11
Beginner amateur Python scripter here (sorry if I unwittingly use incorrect terms). I'm looking to create a countdown timer in Python that takes into account a set date in the future and the current date.
For example, if I wanted to make a "deathclock" (to wit, a countdown timer that counts down to my estimated date of death) the timer would need to count down from the current date to my estimated date of death years in the future, the latter of which would be hard-coded into the Python script.
I imagine I'd have to do something like get the current date, convert it to seconds, subtract it from the date of death (which would also be converted to seconds), and then convert the difference to a years-months-days-hours-minutes-seconds format, which would then be the starting point of the countdown timer (the timer would preferably need to be able to display years, months, days, hours, minutes, and seconds as it counts down).
Is there a relatively simple way to do this so the timer displays in a Linux terminal, or would doing something like this be a pain?
Thanks in advance for any assistance.
Upvotes: 1
Views: 1842
Reputation: 1114
You can get the delta between two times:
from datetime import datetime
my_death = datetime(2044, 3, 24)
lacking = datetime.now() - my_death
This lacking
object has some useful attributes you can use, like lacking.days
and lacking.total_seconds()
.
Upvotes: 2
Reputation: 5560
You have to tell the terminal to overwrite the current line instead of printing to a new line. This will only work on systems that properly handle control characters. It works from a Windows command prompt and I just tested on OSX but doesn't from Idle.
import sys,time
def msg(txt):
sys.stdout.write(txt)
sys.stdout.flush()
for sec in range(10):
time.sleep(1)
m = "%2d seconds" % (10-sec)
msg(m + chr(13))
Regarding the time operations, you can use the datetime
module which lets you compute and format date intervals (like +3 days). https://docs.python.org/2/library/datetime.html
Upvotes: 0