【发布时间】:2022-01-08 17:52:34
【问题描述】:
导入的日期时间,我想验证用户输入的日期以查看它是否与 YYYY-MM-DD 匹配。如果没有,请 print('Sorry wrong format, try again!') 并要求他们再次输入日期。如果他们确实采用了正确的格式,则功能会继续向用户提出下一个问题。现在,我的代码拒绝所有日期格式(即使是正确的)。最终希望将验证函数放在一个单独的函数中,这样它就更干净了。
def add_new_entry(entries):
date = input('When was the transaction? (YYYY-MM-DD): ')
try:
transaction_date = datetime.datetime.strptime(date, "%Y/%m/%D")
except ValueError:
print("Sorry, that is in the incorrect format. Try again!")
return add_new_entry(date)
transaction = input('Was it Income or Expense? ')
amount = input('What was the dollar amout? $')
note = input('Describe the transaction: ')
【问题讨论】:
-
尝试用
"%Y/%m/%d"替换"%Y/%m/%D" -
输入提示信息有破折号,但你的格式字符串有斜杠。
标签: python error-handling