Date Parsing and Validation with Regex

Using regular expressions to parse and validate dates in various formats

Python
import re
from datetime import datetime

def parse_date(date_string):
    patterns = [
        r'^(\d{4})-(\d{2})-(\d{2})$',  # YYYY-MM-DD
        r'^(\d{2})/(\d{2})/(\d{4})$',  # DD/MM/YYYY
        r'^(\d{2})-([A-Za-z]{3})-(\d{4})$'  # DD-Mon-YYYY
    ]
    
    for pattern in patterns:
        match = re.match(pattern, date_string)
        if match:
            try:
                if pattern == patterns[0]:
                    return datetime.strptime(date_string, "%Y-%m-%d")
                elif pattern == patterns[1]:
                    return datetime.strptime(date_string, "%d/%m/%Y")
                else:
                    return datetime.strptime(date_string, "%d-%b-%Y")
            except ValueError:
                return None
    return None

dates = ["2023-04-01", "15/09/2022", "31-Dec-2024", "2023-13-01", "01/15/2022"]
for date in dates:
    parsed_date = parse_date(date)
    if parsed_date:
        print(f"{date}: Valid (Parsed: {parsed_date.strftime('%Y-%m-%d')})")
    else:
        print(f"{date}: Invalid")
Click Run or press shift + ENTER to run code.