Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Validate a date string in YYYY-MM-DD format

Check whether a string is a valid date in strict YYYY-MM-DD format, including leap years.

Python practice14 minError Handling & Edge CasesIntermediateLast updated March 20, 2026

Problem statement

Create a function validate_date(date_str) that returns True if date_str is a valid date in the exact YYYY-MM-DD format, otherwise returns False. The function should: - Require a string input. Non-string inputs return False. - Enforce exactly four digits for the year, two digits for the month, and two digits for the day, separated by single hyphens. - Validate month is 01-12 and day is valid for that month, taking leap years into account. - Reject invalid numeric values (e.g., month 00 or 13, day 00 or out of range). - Reject extra characters, missing parts, or different separators. Write robust defensive checks and handle malformed inputs without raising exceptions.

Task

Write a function that verifies input is a string formatted as YYYY-MM-DD and represents a real calendar date.

Examples

Leap day on a leap year

Input

validate_date('2020-02-29')

Output

True

2020 is a leap year and 02-29 is a valid date.

Input format

A single argument: date_str (string) to validate.

Output format

Return True if valid YYYY-MM-DD date, otherwise False.

Constraints

Do not use uncontrolled exception propagation. Use standard library if helpful. Year must be exactly 4 digits, month/day exactly 2 digits.

Samples

Sample 1

Input

validate_date('2019-02-28')

Output

True

2019-02-28 is a valid non-leap-year date.