簡體   English   中英

Python - datetime - 檢查用戶輸入的日期是否匹配格式

[英]Python - datetime - Check if user input date matches format

導入日期時間,我想驗證用戶輸入日期以查看它是否與 YYYY-MM-DD 匹配。 如果沒有,請 print('Sorry wrong format, try again.') 並要求他們再次輸入日期,如果他們確實輸入了正確的格式。 function 繼續向用戶提出下一個問題,現在。 我的代碼拒絕所有日期格式(即使是正確的)。 最終希望在單獨的 function 中驗證 function,這樣它就更干凈了。

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 strftime() 和 strptime() 格式代碼的文檔

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())

Output:

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 ,您想讓用戶重新輸入日期。

參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM