Best Way To Validate An Entered Date

Ubuntu 22.04 Python 3.12 pycharm 2023.3.3

Hi.
I’m starting to play with python and I am liking it very much. I have written a snippet of code to test the validity of an entered date, and I would like to know if this is the best way of doing so:

from datetime import datetime
# Validate Date Entry
while(True):
    try:
        DDate = input("Enter Date yyyymmdd: ")
        datetime = datetime.strptime(DDate, '%Y%m%d')   # Error Test
        if len(DDate) != 8:  # Length must be 8
            raise Exception
        else:
            break    # Break pulls you out of the loop
    except:
        print("INVALID Date: ",DDate)

print("Valid Date Has Been Entered: ",DDate)

Thank you in advance for your help,
M…

Welcome to Python!

If you 100% want that particular format, what you have can work.

If the format isn’t as guaranteed, I would recommend using something like dateutil.parser’s parse() method. It tries to ‘get a datetime object from the given string’.

In [1]: from dateutil.parser import parse

In [2]: parse("20240325")
Out[2]: datetime.datetime(2024, 3, 25, 0, 0)

In [3]: parse("20240326 16:00 UTC")
Out[3]: datetime.datetime(2024, 3, 26, 16, 0, tzinfo=tzutc())

dateutil can be obtained via pip install python-dateutil. More docs on this: parser — dateutil 3.9.0 documentation.

If len(DDate) doesn’t equal 8, the call to datetime.strptime will raise a ValueError. If you want to check the length, you need to do so before calling strptime, but since strptime can already catch that error, there’s no need for an explicit length check. Just let strptime do its thing, but be prepared to catch an exception.

while True:
    date_str = input("Enter Date yyyymmdd: ")
    try:
        d = datetime.stptime(date_str, '%Y%m%d')
        break
    except ValueError:
        print("Invalid yyyymmdd string, '{date_str}', try again")
print("Valid date has been entered: date_str")

strptime guarantees that its input was valid if it returns at all, so if no exception is raised, you can immediately break out of the loop. If there is an exception, notify the user and let the loop continue as usual.

Hi.
Thanks for the informative response.
Below I have validated a Date Entry via .strptime and as per your advice, via Parse. Both methods seem to work really well. Is one method better than the other ?

# Validate Date entry via Parse
from dateutil.parser import parse
while(True):
    try:
        DDate = input("Enter Date yyyymmdd: ")
        DDate = parse(DDate)  # Error Test parse
        break    # Break pulls you out of the loop
    except:
        print("INVALID Date: ",DDate)

print("Valid Date Has Been Entered: ",DDate)

#       OR

# Validate Date Entry via .strptime
while(True):
    try:
        DDate = input("Enter Date yyyymmdd: ")
        DDate = datetime.strptime(DDate, '%Y%m%d')  # Error Test .strptime
        break    # Break pulls you out of the loop
    except ValueError:
        print("INVALID Date: ",DDate)

print("Valid Date Has Been Entered: ",DDate)


Thanks for your help,
M....

dateutil.parser.parse gives the user more flexibility when inputting the date format. It’s up to you what you think the program ought to accept. You can read the documentation that Charles linked to you in order to understand what inputs the user can now use, and decide for yourself if that’s a good idea (and if you want to add a third-party library to support it).

Thanks All. Python is awesome!
M…

To validate if a string is a valid date input, you need to call the Date() constructor and pass the string as its argument . Note that the Date() constructor requires you to pass a date in the format of YYYY/MM/DD or MM/DD/YYYY . If you pass a date in DD/MM/YYYY format, the contructor also returns an Invalid Date.