Count down to a target datetime in Python [closed]

空扰寡人 提交于 2019-12-11 06:35:34

问题


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?


回答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)

def countdown() : 
    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)

def countdown() : 
    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 :

2396
2395
2394
2393
...


来源:https://stackoverflow.com/questions/43007345/count-down-to-a-target-datetime-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!