Skip to content Skip to sidebar Skip to footer

Count Down To A Target Datetime In Python

I am trying to create a program which takes a target time (like 16:00 today) and counts down to it, printing each second like this: ... 5 4 3 2 1 Time reached How can I do this?

Solution 1:

You can do this using python threading module also, something like this :

from datetime import datetime
import threading

selected_date = datetime(2017,3,25,1,30)

defcountdown() : 
    t = threading.Timer(1.0, countdown).start()
    diff = (selected_date - datetime.now())
    print diff.seconds
    if diff.total_seconds() <= 1 :    # To run it once a day
        t.cancel()

countdown()

For printing "Click Now" when countdown gets over, you can do something like this :

from datetime import datetime
import threading

selected_date = datetime(2017,3,25,4,4)

defcountdown() : 
    t = threading.Timer(1.0, countdown)
    t.start()
    diff = (selected_date - datetime.now())
    if diff.total_seconds() <= 1 :    # To run it once a day
        t.cancel()
        print"Click Now"else :
        print diff.seconds
countdown()

This will result in something like this every second :

2396239523942393...

Post a Comment for "Count Down To A Target Datetime In Python"