標題中的問題。我正在編寫一個程序,要求用戶以mm/dd/yy格式輸入日期,如果日期僅在2013年,請驗證該日期,然後以此格式打印日期:2013年7月1日。 「M剛剛在一個邏輯錯誤的程序仍然會打印出日期,即使一年不2013年。這裏是我的代碼:如何在Python中設置最小和最大日期以驗證輸入?
import datetime
def main():
def date_method(user_date):
date_list = user_date.split('/')
month = int(date_list[0])
day = int(date_list[1])
year = 2000 + int(date_list[2])
try:
datetime.datetime.min = 1/1/2013
datetime.datetime.max = 12/31/2013
the_date = datetime.date(month, day, year)
correct_date = "True"
return the_date, correct_date
except ValueError as err:
print(err)
the_date = 1/1/1
correct_date = "False"
return the_date, correct_date
correct_date = "False"
while correct_date == "False":
user_date = str(input("Please enter a date in the month/day/year format: mm/dd/yy. "))
the_date, correct_date = date_method(user_date)
if correct_date == "True":
print("Date: ", datetime.date.strftime(the_date, "%B %d, %y"))
main()
當我覺得我離我datetime.datetime.min和datetime.datetime.max變量。
您是否嘗試添加年份變量的if/else語句?這似乎更簡單。 – macmania314
你知道'/'是用來劃分的嗎? –
是的,我現在意識到這一點。我的錯。 – Jasonca1