Write a Python function that accepts a string representing a date (in the format “YYYY-MM-DD”) and raises custom exceptions for scenarios like an invalid month (greater than 12), invalid day (greater than 31), etc.
Example 1:
Input: "2023-13-20" Output: "Error: Invalid month."
Example 2:
Input: "2023-11-31" Output: "Error: Invalid day."
Use the datetime
module to parse the date string.
from datetime import datetime def validate_date(date_str): try: datetime.strptime(date_str, '%Y-%m-%d') return "Valid date." except ValueError: raise Exception("Error: Invalid date.") print(validate_date("2023-13-20")) # Output: "Error: Invalid date." print(validate_date("2023-11-30")) # Output: "Valid date."
Unlock AI & Data Science treasures. Log in!