How to do date validation in Python?

In this article, we will show you how to do date validation in Python. Date validation ensures that date strings conform to expected formats and represent valid dates.

Using datetime.strptime() Function

The datetime.strptime() function parses a date string according to a specified format. It raises a ValueError if the date is invalid or doesn't match the format ?

import datetime

# Valid date string
date_string = '2017-12-31'
date_format = '%Y-%m-%d'

try:
    # Parse the date string
    date_object = datetime.datetime.strptime(date_string, date_format)
    print(f"Valid date: {date_object}")
except ValueError:
    print("Invalid date format, should be YYYY-MM-DD")
Valid date: 2017-12-31 00:00:00

Testing with Invalid Date

Here's an example with an invalid date to demonstrate error handling ?

import datetime

# Invalid date string (February 30th doesn't exist)
date_string = '2021-02-30'
date_format = '%Y-%m-%d'

try:
    date_object = datetime.datetime.strptime(date_string, date_format)
    print(f"Valid date: {date_object}")
except ValueError:
    print("Invalid date: February 30th doesn't exist")
Invalid date: February 30th doesn't exist

Common Format Directives

The strptime() function supports various format directives ?

Directive Meaning Example
%Y Year with century 2021
%m Month as decimal [01,12] 12
%d Day of month [01,31] 31
%B Full month name December
%A Full weekday name Monday

Using dateutil.parser.parse() Function

The dateutil library provides more flexible date parsing without requiring a specific format string ?

from dateutil import parser

# Valid date in different format
date_string = '12/31/2021'

try:
    parsed_date = parser.parse(date_string)
    print(f"Parsed date: {parsed_date}")
    print(f"Is valid: {bool(parsed_date)}")
except ValueError:
    print("Invalid date format")
Parsed date: 2021-12-31 00:00:00
Is valid: True

Testing Invalid Date with dateutil

from dateutil import parser

# Invalid date string
date_string = '41-23-2021'  # Invalid month (41)

try:
    parsed_date = parser.parse(date_string)
    print(f"Parsed date: {parsed_date}")
except ValueError:
    print("Invalid date format")
Invalid date format

Creating a Date Validation Function

Here's a reusable function that combines both approaches ?

import datetime
from dateutil import parser

def validate_date(date_string, date_format=None):
    """Validate date using datetime.strptime or dateutil.parser"""
    
    if date_format:
        # Use strptime with specific format
        try:
            datetime.datetime.strptime(date_string, date_format)
            return True
        except ValueError:
            return False
    else:
        # Use dateutil parser for flexible parsing
        try:
            parser.parse(date_string)
            return True
        except ValueError:
            return False

# Test the function
test_dates = ['2021-12-31', '2021-02-30', 'Dec 31, 2021', 'invalid-date']

for date in test_dates:
    is_valid = validate_date(date)
    print(f"{date}: {'Valid' if is_valid else 'Invalid'}")
2021-12-31: Valid
2021-02-30: Invalid
Dec 31, 2021: Valid
invalid-date: Invalid

Comparison

Method Format Required Flexibility Best For
datetime.strptime() Yes Low Strict format validation
dateutil.parser.parse() No High Flexible date parsing

Conclusion

Use datetime.strptime() when you need strict format validation with specific date formats. Use dateutil.parser.parse() for flexible parsing of various date string formats without predefined patterns.

Updated on: 2026-03-24T19:33:34+05:30

33K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements