简体   繁体   中英

Dynamic Python Countdown Timer

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.

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() .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM