我正在对用户输入日期进行计数。我被卡住了,不知道如何打印小时,分钟,秒。例如,用户输入为:2019-03-10,因此脚本需要递减计数:还剩6天23小时59分20秒,还剩23小时59分19秒等。 有什么建议怎么做吗?
我的代码:
import datetime
import time
current_date = datetime.date.today()
print('Today is: ' + str(current_date))
def getdate():
year = int(input('Enter a year: '))
month = int(input('Enter a month: '))
day = int(input('Enter a day: '))
date_user = datetime.date(year, month, day)
print(date_user)
if date_user < current_date:
print('This is past bro, wake up!')
exit()
elif date_user > current_date:
print((date_user - current_date))
getdate()
答案 0 :(得分:0)
这是一个例子。
注意:
import datetime
import time
current_date = datetime.datetime.now() # Now gives current minutes, seconds...
print('Today is: ' + str(current_date))
def getdate():
year = int(input('Enter a year: '))
month = int(input('Enter a month: '))
day = int(input('Enter a day: '))
date_user = datetime.datetime(year, month, day, 0, 0, 0) # Midnight
return date_user
date_user = getdate()
while date_user > current_date:
current_date = datetime.datetime.now()
diff = date_user - current_date
# Using https://stackoverflow.com/a/539360/8575607
s = diff.seconds
# hours
hours = s // 3600
# remaining seconds
s = s - (hours * 3600)
# minutes
minutes = s // 60
# remaining seconds
seconds = s - (minutes * 60)
print("{}day(s) {}h {}min(s) {}sec(s) left".format(diff.days, hours, minutes, seconds), end='\r')
time.sleep(1)
print('\nThis is past bro, wake up!')
我建议您下次更好地说明您的问题。例如:“如何通过以下方式打印时间增量?”或“如何每秒执行一行代码,直到达到目标?”您去询问更大的情况,而通常情况下却没有给您有用的答案^^