0

I am new here and I was hoping someone could help me out with a project I'm attempting to create. Using Python I would like to make a countdown clock from user-specific information that, when getting a month day and year, would finish by printing an active countdown clock for that specific date. Is this possible? If so, how?

Thanks in advance. -Anthony

enamoria
  • 896
  • 2
  • 11
  • 29

1 Answers1

0

The code below can be a start. The function date_countdown takes in a date string and a date format corresponding to the date string, and outputs a countdown to the terminal.

countdown.py

import datetime

def date_countdown(future_datetime, date_format):
    print("Countdown for {}:".format(future_datetime))
    seconds_left = -1
    while seconds_left:
        cur = datetime.datetime.now()
        fut = datetime.datetime.strptime(future_datetime, date_format)
        left = fut - cur
        print(
            "{0: >3d} days, {1:0>2d}:{2:0>2d}:{3:0>2d}".format(
                left.days, # days
                left.seconds // 3600, # hours
                (left.seconds // 60) % 60, # minutes
                (left.seconds % 60) # seconds
            ),
            end='\r')
        time.sleep(1)
        seconds_left = left.total_seconds()
    print('Done!')

date_countdown('2018-12-25', '%Y-%m-%d')

Output:

Countdown for 2018-12-25:
 27 days, 04:15:40
  • This is great, thanks. I really do appreciate the help. My only other issue is adding in user input so it can be the countdown for whatever date the user intends on counting down to. How would I implement the input into this code? Thanks again. – Anthony DiPerri Nov 28 '18 at 16:46
  • You could do `date_countdown(input("Type a date (YYYY-MM-DD): "), '%Y-%m-%d')` to ask the user to input a date in the command line. – Edgar Ramírez Mondragón Nov 28 '18 at 23:00
  • this was all very helpful, if i could ask another question.. ive been scouring the internet for a reasonable answer to this: can i force python to overwrite the current line each time the countdown advances as opposed to it creating a new line? – Anthony DiPerri Nov 29 '18 at 14:52
  • Using the carriage return character `\r` in the print statement as in `date_countdown`. There's no other way that I know of. – Edgar Ramírez Mondragón Nov 29 '18 at 17:07