我是一個但堅持能夠將用戶定義的日期添加到這個 Days to Go 代碼中。適用于嵌入的設定日期。但不能讓它與輸入線一起作業。
from datetime import datetime, time
b = input
event = (input('What is the name of your event?')) # input the name of the event
year = int(input('Enter a year')) # input the requires year
month = int(input('Enter a month')) # input the required month
day = int(input('Enter a day')) # input the required day
def date_diff_in_seconds(dt2, dt1):
timedelta = dt2 - dt1
return timedelta.days * 24 * 3600 timedelta.seconds
def dhms_from_seconds(seconds):
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
return (days, hours, minutes, seconds)
# Specified date
date1 = datetime.date(b[1], b[2], b[3])
# Current date
date2 = datetime.now()
print("\n%d days, %d hours, %d minutes, %d seconds" %
dhms_from_seconds(date_diff_in_seconds(date2, date1)))
print()
uj5u.com熱心網友回復:
首先,你錯誤地使用了b=input. 這意味著您要使用input函式名稱為 b 的函式,例如event = b('what is the name of your event?').
相反,您可以b在b = (event, year, month, day)使用input().
而你匯入datetime的模塊from datetime import datetime你不需要明確地說datetime.date,只是date。但是,您可以使用datetime而不是date此處,如下所示:
from datetime import datetime, time
#b = input -> wrong usage
event = (input('What is the name of your event? ')) # input the name of the event
year = int(input('Enter a year ')) # input the requires year
month = int(input('Enter a month ')) # input the required month
day = int(input('Enter a day ')) # input the required day
b = (event, year, month, day) # you can assign date values to b
def date_diff_in_seconds(dt2, dt1):
timedelta = dt2 - dt1
return timedelta.days * 24 * 3600 timedelta.seconds
def dhms_from_seconds(seconds):
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
return (days, hours, minutes, seconds)
# Specified date
date1 = datetime(b[1], b[2], b[3]) # not datetime.date()
# Current date
date2 = datetime.now()
print("\n%d days, %d hours, %d minutes, %d seconds" %
dhms_from_seconds(date_diff_in_seconds(date2, date1)))
print()
# if you want to print the event together:
print("\n%d days, %d hours, %d minutes, %d seconds left for %s" % (
dhms_from_seconds(date_diff_in_seconds(date2, date1)) (event,)))
結果是這樣的:
What is the name of your event? birthday
Enter a year 2022
Enter a month 03
Enter a day 19
0 days, 14 hours, 40 minutes, 2 seconds
0 days, 14 hours, 40 minutes, 2 seconds left for Sunday # in case that you print the event together
uj5u.com熱心網友回復:
我認為你的問題很可能是這一行:
date1 = datetime.date(b[1],b[2],b[3])
嘗試將其更改為:
date1 = datetime.date(year, month, day, 0, 0, 0)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/447515.html
標籤:Python python-3.x 日期 用户输入
