Date String to Datetime Object Conversion

Write a Python function that takes a date string in the format “YYYY-MM-DD” and converts it to a DateTime object. The function should handle incorrect formats.

Example 1:

Input: "2023-08-02"
Output: datetime.datetime(2023, 8, 2, 0, 0)

Example 2:

Input: "02-08-2023"
Output: "Exception: Incorrect date format"

Use Python’s datetime module to convert the date string to a datetime object.

from datetime import datetime

def convert_date(date_str):
    try:
        return datetime.strptime(date_str, "%Y-%m-%d")
    except ValueError:
        return "Exception: Incorrect date format"

 

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!