如何使用 Python 3 正确显示倒计时日期

2024-05-15

我正在尝试获取将显示的倒计时。基本上就像一个世界末日时钟哈哈。

有人可以帮忙吗?

import os
import sys
import time
import datetime

def timer():
    endTime = datetime.datetime(2019, 3, 31, 8, 0, 0)

def countdown(count):
    while (count >= 0):
        print ('The count is: ', count)
        count -= 1
        time.sleep(1)

countdown(endTime)
print ("Good bye!")

如果您想像世界末日时钟一样打印倒计时,则需要解析 timedelta 值。

您正在寻找这样的东西吗?

import time
import datetime


def countdown(stop):
    while True:
        difference = stop - datetime.datetime.now()
        count_hours, rem = divmod(difference.seconds, 3600)
        count_minutes, count_seconds = divmod(rem, 60)
        if difference.days == 0 and count_hours == 0 and count_minutes == 0 and count_seconds == 0:
            print("Good bye!")
            break
        print('The count is: '
              + str(difference.days) + " day(s) "
              + str(count_hours) + " hour(s) "
              + str(count_minutes) + " minute(s) "
              + str(count_seconds) + " second(s) "
              )
        time.sleep(1)


end_time = datetime.datetime(2019, 3, 31, 19, 35, 0)
countdown(end_time)

# sample output
The count is: 44 day(s) 23 hour(s) 55 minute(s) 55 second(s) 
The count is: 44 day(s) 23 hour(s) 55 minute(s) 54 second(s) 
The count is: 44 day(s) 23 hour(s) 55 minute(s) 53 second(s) 
The count is: 44 day(s) 23 hour(s) 55 minute(s) 52 second(s) 
The count is: 44 day(s) 23 hour(s) 55 minute(s) 51 second(s) 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Python 3 正确显示倒计时日期 的相关文章