Python
Date Validation
Date String
Programming
Code Snippets

Check if a string is a valid date format in Python

Codemia Knowledge Hub ·

Call datetime.strptime(value, fmt) and catch ValueError. That one call checks both things you care about: the text matches the expected format, and it is a real calendar date. Regex alone only covers the first.

Validating with datetime.strptime

strptime() parses according to a format string and raises ValueError if the input is malformed or impossible:

python
1from datetime import datetime
2
3def is_valid_date(value: str, fmt: str = "%Y-%m-%d") -> bool:
4    try:
5        datetime.strptime(value, fmt)
6        return True
7    except ValueError:
8        return False
9
10print(is_valid_date("2026-03-07"))
11print(is_valid_date("2026-02-31"))
12print(is_valid_date("07/03/2026"))

2026-02-31 fails even though it looks like a date, because February has no 31st day.

Why regex is not enough

A regex can confirm the string looks like YYYY-MM-DD, but it cannot easily tell whether the date is real:

python
1import re
2
3pattern = re.compile(r"^\d{4}-\d{2}-\d{2}$")
4
5print(bool(pattern.fullmatch("2026-03-07")))
6print(bool(pattern.fullmatch("2026-99-99")))

The second value matches but is not a valid date. If you use a regex, treat it as a shape pre-filter and still pass the string to strptime().

Enforcing the exact format with a round trip

Some inputs parse successfully without matching the exact format you require. To reject them, parse and then format back to a string:

python
1from datetime import datetime
2
3def is_strict_date(value: str, fmt: str = "%Y-%m-%d") -> bool:
4    try:
5        parsed = datetime.strptime(value, fmt)
6        return parsed.strftime(fmt) == value
7    except ValueError:
8        return False
9
10print(is_strict_date("2026-03-07"))
11print(is_strict_date("2026-3-7"))

This suits APIs, CSV imports, and forms where canonical formatting matters as much as calendar correctness.

Accepting several explicit formats

If you accept more than one format, list them explicitly rather than falling back to fuzzy parsing, unless ambiguity is truly acceptable:

python
1from datetime import datetime
2
3ACCEPTED_FORMATS = ("%Y-%m-%d", "%d/%m/%Y", "%m-%d-%Y")
4
5def parse_date(value: str):
6    for fmt in ACCEPTED_FORMATS:
7        try:
8            return datetime.strptime(value, fmt)
9        except ValueError:
10            pass
11    return None
12
13print(parse_date("2026-03-07"))
14print(parse_date("07/03/2026"))
15print(parse_date("bad-input"))

Anyone reading the code can see exactly which formats are allowed.

Returning an error message instead of False

A boolean is fine for quick filters, but callers often need the parsed date or a reason for the failure:

python
1from datetime import datetime
2
3def validate_date(value: str, fmt: str = "%Y-%m-%d"):
4    try:
5        return True, datetime.strptime(value, fmt).date()
6    except ValueError as exc:
7        return False, str(exc)
8
9print(validate_date("2026-03-07"))
10print(validate_date("2026-02-31"))

This helps in data-import tools, where you want to report why a row failed instead of silently dropping it.

Date-only versus date-time inputs

Decide early whether the contract is date-only or a full timestamp. If the input can include hours, minutes, or time zone information, validate against that full format rather than trimming the value:

python
1from datetime import datetime
2
3value = "2026-03-07 14:30"
4parsed = datetime.strptime(value, "%Y-%m-%d %H:%M")
5print(parsed)

Mixing date-only and date-time rules in one validator creates confusing edge cases.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms