Parse dates defensively and distinguish missing input from malformed input.
How It Works
A missing date might mean an optional field, while an invalid date such as February 30 is a data error. Strip input only after checking its type, parse a documented format, then return a useful validation message. Avoid quietly replacing invalid dates with the current day.
Keep empty, invalid and valid date states separate when designing forms and APIs.
Step-by-Step Example
from datetime import date
def parse_optional_date(text):
if text is None or text == "":
return None
if not isinstance(text, str):
raise TypeError("date must be a string")
try:
return date.fromisoformat(text)
except ValueError as exc:
raise ValueError("Use YYYY-MM-DD for dates") from exc
print(parse_optional_date("2026-10-17"))
print(parse_optional_date(None))
Understanding the Example
- The function definition gives the operation a reusable name and makes its inputs explicit.
- The condition decides whether the following indented statements run; change its input to see the alternate path.
A successful run of this example prints the following output:
2026-10-17
None
Where This Fits in a Real Program
For event timestamps, distinguish the displayed local clock from the instant that it represents. Store or exchange an unambiguous aware value, then convert it when displaying it to a user. For repeated calendar appointments, use a geographic timezone so daylight-saving rules are not lost.
Practice: Try It Yourself
Pass 2026-02-30 and update the function to show a friendly field-specific error.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Using today as the default for a malformed date and hiding invalid source data.
- Catching ValueError around too much unrelated code and blaming the wrong input field.
Key Takeaways
- Parse dates defensively and distinguish missing input from malformed input.
- A missing date might mean an optional field, while an invalid date such as February 30 is a data error.
- Keep empty, invalid and valid date states separate when designing forms and APIs.