【问题标题】:Python - datetime - Check if user input date matches formatPython - datetime - 检查用户输入日期是否与格式匹配
【发布时间】: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


【解决方案1】:

日期格式不正确。应该是%Y-%m-%dDocumentation of the strftime() and strptime() Format Codes

import datetime


def add_new_entry():
    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()
    transaction = input('Was it Income or Expense? ')
    amount = input('What was the dollar amount? $')
    note = input('Describe the transaction: ')
    return date, transaction, amount, note


print(add_new_entry())

输出:

When was the transaction? (YYYY-MM-DD): 2022-01-69
Sorry, that is in the incorrect format. Try again!
When was the transaction? (YYYY-MM-DD): 2022-23-32
Sorry, that is in the incorrect format. Try again!
When was the transaction? (YYYY-MM-DD): 2022-01-08
Was it Income or Expense? Income
What was the dollar amount? $2222
Describe the transaction: Salary
('2022-01-08', 'Income', '2222', 'Salary')

说明:

  • 在执行except 块时,我已删除参数date,因为我假设您想让用户重新输入日期。

参考资料:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-28
    • 1970-01-01
    • 2018-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多