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

问题描述 投票:0回答:2

我想要显示一个倒计时。基本上就像世界末日时钟哈哈。

可能有人能够提供帮助吗?

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!")
python date timer countdown
2个回答
1
投票

如果实现datetime方法,可以使用datetime.datetime.now()模块轻松完成此操作。看看这个:

import datetime

present = datetime.datetime.now()
future = datetime.datetime(2019, 3, 31, 8, 0, 0)
difference = future - present
print(difference)

产出:16天,8:19:46.639633


0
投票

如果你想像世界末日时钟那样打印倒计时,你需要解析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) 
© www.soinside.com 2019 - 2024. All rights reserved.