在Python中倒数到目标日期时间 [英] Count down to a target datetime in Python

查看:165
本文介绍了在Python中倒数到目标日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个需要目标时间(例如今天的16:00)并倒计时的程序,像这样每秒打印一次:

  ... 
5
4
3
2
1
到达时间

我该怎么做?

解决方案

您也可以使用python threading 模块执行此操作,例如:

  from datetime导入datetime 
导入线程

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

def countdown():
t = threading.Timer(1.0,countdown).start()
diff =(selected_date-datetime.now())
打印差异秒
如果diff.total_seconds()< = 1:#每天运行一次
t.cancel()

countdown()

要在倒计时结束后打印立即单击,您可以执行以下操作:



<$ p $从datetime导入datetim起p> e
导入线程

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

def countdown():
t = threading.Timer (1.0,倒数)
t.start()
diff =(selected_date-datetime.now())
if diff.total_seconds()< = 1:#一次运行一次day
t.cancel()
print Click Now
else:
print diff.seconds
countdown()

这将导致这样的结果每秒

  2396 
2395
2394
2393
...


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?

解决方案

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
...

这篇关于在Python中倒数到目标日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆