Home > database >  How do I validate a date format with python?
How do I validate a date format with python?

Time:10-17

I'm a Software Development student, and currently stuck on validating a date format with Python. I'm currently learning validations and can't really find anything that quite answers the question for what I want to do.

This is the code I want to verify:

InvDateStr = input("Enter the invoice date (YYYY-MM-DD): ")
InvDate = datetime.datetime.strptime(InvDateStr, "%Y-%m-%d")

if InvDate == "":
        print("Invoice date cannot be blank. Please re-enter.")
else:
    break

Thanks in advance!

CodePudding user response:

InvDateStr = input("Enter the invoice date (YYYY-MM-DD): ")
try:
    InvDate = datetime.datetime.strptime(InvDateStr, "%Y-%m-%d")
except:
    print("Provided date format is wrong")

Alternatively, you can use parse method of dateutil.parser

from dateutil.parser import parse
InvDateStr = input("Enter the invoice date (YYYY-MM-DD): ")
try:
    InvDate = parse(InvDateStr)
except ValueError as e:
    print(e)

CodePudding user response:

You can use exceptions to catch when date is invalid, for example:

import datetime

InvDateStr = input("Enter the invoice date (YYYY-MM-DD): ")

try:
    InvDate = datetime.datetime.strptime(InvDateStr, "%Y-%m-%d")
    print("Date valid")
except ValueError:
    print("Date invalid")

Prints:

Enter the invoice date (YYYY-MM-DD): 2003-02-29
Date invalid
  • Related