How do I validate a date format with python?

Question:

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!

Asked By: jonahpocalypse

||

Answers:

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
Answered By: Andrej Kesely
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)
Answered By: Nazmus Sakib
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.