【问题标题】:Count down to a target datetime in Python [closed]在Python中倒计时到目标日期时间[关闭]
【发布时间】:2017-08-17 20:31:07
【问题描述】:

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

...
5
4
3
2
1
Time reached

我该怎么做?

【问题讨论】:

  • 这是一个合理的问题,幼稚的解决方案是行不通的。显而易见的方法是有一个循环,在该循环中您反复休眠一秒钟,然后打印剩余时间,但是由于非休眠操作需要时间来执行,因此循环将偏离恰好一秒钟的时间来执行。如果您使用递减整数跟踪剩余的秒数,那么您将迟到 0;但是如果您通过获取当前时间来计算每次迭代的时间,您可能会在输出中跳过一秒钟。这种细微差别很有趣,这个问题不值得结束。

标签: python datetime time timer clock


【解决方案1】:

您也可以使用 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()

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

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

【讨论】:

  • .total_seconds() 如果您希望它在多天内工作。否则它将在任何天的那个时候熄灭。
  • @TemporalWolf OP 要求到那时为止的每一天,对吧?
  • 你是对的。如果您在时间为 0 时触发,这应该可以工作。
  • @SatishGarg 当我尝试运行代码时,它说没有名为 seconds 的属性
  • 检查日期时间导入和括号。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-04
  • 2020-09-04
  • 2013-06-15
  • 1970-01-01
相关资源
最近更新 更多