easy +10 pts

Validate date format

Check if a string matches the YYYY-MM-DD calendar format

Write a function `is_valid_date(date_str)` that takes a string and returns `True` if the string represents a valid date in the format `YYYY-MM-DD` (4-digit year, 2-digit month, 2-digit day, separated by hyphens). The date must be a real calendar date (e.g., 2023-02-29 is invalid, 2020-02-29 is valid because 2020 is a leap year). The year must be between 0001 and 9999 inclusive (i.e., exactly 4 digits).

Constraints

Input is a string of arbitrary content (may be empty). Output must be a boolean. Do not use external libraries (e.g., datetime).

Example

>>> is_valid_date('2023-12-31')
True
>>> is_valid_date('2023-02-29')
False
>>> is_valid_date('20-01-01')
False
>>> is_valid_date('2020-02-29')
True
10 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use split('-') to separate the string into parts. Check that there are exactly 3 parts and each part is numeric.
Check the length of the year string is 4, month is 2, day is 2, and that month is 01-12.
Remember leap year rule: divisible by 4 but not by 100 unless also divisible by 400.
For February, the max day is 29 in a leap year, otherwise 28; for other months use 30 or 31.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.