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

在Python中倒计时到目标日期时间,python,datetime,time,timer,clock,Python,Datetime,Time,Timer,Clock,我正在尝试创建一个程序,它需要一个目标时间,比如今天16:00,然后倒计时,每秒钟打印一次,如下所示: ... 5 4 3 2 1 Time reached 我如何才能做到这一点?您也可以使用python线程模块来做到这一点,类似于: from datetime import datetime import threading selected_date = datetime(2017,3,25,1,30) def countdown() : t = threading.Time

我正在尝试创建一个程序,它需要一个目标时间,比如今天16:00,然后倒计时,每秒钟打印一次,如下所示:

...
5
4
3
2
1
Time reached

我如何才能做到这一点?

您也可以使用python线程模块来做到这一点,类似于:

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

.如果您希望它在多天内工作,则为总秒数。否则它会在任何一天的那个时候爆炸。@TemporalWolf OP要求在那个时候之前的每一天,对吗?你是对的。如果您在时间为0时触发,这应该可以工作。@SatishGarg当我尝试运行代码时,它说没有名为second的属性请检查日期时间导入和括号。这是一个合理的问题,一个简单的解决方案无法解决。最明显的方法是使用一个循环,在该循环中重复睡眠一秒钟,然后打印剩余时间,但由于非睡眠操作需要时间来执行,因此循环将漂移,只需要一秒钟的时间来执行。如果您使用递减整数跟踪剩余的秒数,那么您将延迟到达0;但是,如果您通过获取当前时间来计算每次迭代的时间,您可能会在输出中跳过一秒钟。这种细微差别很有趣,这个问题不值得结束。
2396
2395
2394
2393
...