倒计时到 Python 中的目标日期时间

Count down to a target datetime in Python

我正在尝试创建一个程序,它需要一个目标时间(比如今天 16:00)并倒计时,每秒打印如下:

...
5
4
3
2
1
Time reached

我该怎么做?

您也可以使用 python threading 模块来执行此操作,如下所示:

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

要在倒计时结束时打印 "Click Now",您可以这样做:

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

这将导致这样的结果 每秒 :

2396
2395
2394
2393
...