倒数计时器给我负数

时间:2015-12-14 02:00:25

标签: python python-3.x

我在Python3中制作了一个倒数计时器。我已将月份设置为1,将日期设置为10,仅作为示例。当我运行它时,我得到负数,因为该日期已经过去了。

那么我的问题是如何将年份设置为类似2017的内容,以便获得类似392天的内容,而不是获得负数。

倒数计时器

import time
from datetime import datetime

while True:
    Datetime = datetime.now()
    Month = 1 - Datetime.month
    Day = 10 - Datetime.day
    Hour = 24 - Datetime.hour
    Minute = 60 - Datetime.minute
    Second = 60 - Datetime.second

    Month = str(Month) + " " + "Month"
    Day =  str(Day) + " " + "Day"
    Hour = str(Hour) + " " + "Hour"
    Minute = str(Minute) + " " + "Minute"
    Second = str(Second) + " " + "Second"

    print(Month)
    print(Day)
    print(Hour)
    print(Minute)
    print(Second)

    time.sleep(1)

1 个答案:

答案 0 :(得分:2)

您不需要手动计算。只需使用datetime模块的功能即可。它提供时间增量计算:

import datetime
import time

target_date = datetime.datetime(2017, 1, 11)
timedelta_zero = datetime.timedelta(0)

while True:
    diff = target_date - datetime.datetime.now()
    if diff <= timedelta_zero:
        break
    print(diff)
    time.sleep(1)
print('Takeoff!!!')  

打印:

393 days, 17:09:19.278093
393 days, 17:09:18.276930
393 days, 17:09:17.274710
393 days, 17:09:16.272841
393 days, 17:09:15.270777
393 days, 17:09:14.268744
393 days, 17:09:13.267112

如果您不喜欢微秒,请将其剥离:

>>> print(str(diff).rsplit('.')[0])
393 days, 17:09:19

您的时间差值比较需要datetime.timedelta(0)作为零值。 要进行测试,请将target_date设置为将来几秒钟的日期。应该没有负面日期。