2

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!

2 Answers2

2

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
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • Unfortunately it doesn't look like this worked, unless I did something wrong? This is the code I used: InvDateStr = input("Enter the invoice date (YYYY-MM-DD): ") InvDate: datetime = datetime.datetime.strptime(InvDateStr, "%Y-%m-%d") 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") and this is the error: (in next comment) – jonahpocalypse Oct 17 '22 at 11:46
  • Traceback (most recent call last): File "/Users/keyinstudent/PycharmProjects/Lesson13/QAP3/main.py", line 12, in InvDate: datetime = datetime.datetime.strptime(InvDateStr, "%Y-%m-%d") File (continued in next comment) – jonahpocalypse Oct 17 '22 at 11:48
  • "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/_strptime.py", line 568, in _strptime_datetime tt, fraction, gmtoff_fraction = _strptime(data_string, format) File"/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/_strptime.py", line 349, in _strptime raise ValueError("time data %r does not match format %r" % ValueError: time data '1990.03.30' does not match format '%Y-%m-%d' – jonahpocalypse Oct 17 '22 at 11:48
  • Actually, I have it working! I commented out my first two lines of code, and just used the code you provided. Thanks a lot! – jonahpocalypse Oct 17 '22 at 11:53
2
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)
Nazmus Sakib
  • 68
  • 1
  • 6