我在 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)

最佳答案

您无需手动计算。只需使用 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 设置为 future 几秒钟的日期。不应该有负日期。

关于python - 倒数计时器给我负数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34258677/

10-12 23:23