Python: Convert Date to DateTime


We need to make use of the datetime module methods such as combine, fromisoformat to convert a date to datetime in Python Programming.


Example 1: Using Python 2.x

    import datetime
    
    date = datetime.date(2023, 7, 23)
    datetime_obj = datetime.datetime.combine(date, datetime.time())
    print(datetime_obj)
    Output:

    2023-07-23 00:00:00



Example 2: Using Python 3.x (using fromisoformat())

    import datetime
    
    date = datetime.date(2023, 7, 24)
    date_str = str(date)
    datetime_obj = datetime.datetime.fromisoformat(date_str)
    print(datetime_obj)
    Output:

    2023-07-24 00:00:00



Example 3: Using Python 3.x (using combine())

    import datetime
    
    date = datetime.date(2023, 7, 25)
    datetime_obj = datetime.datetime.combine(date, datetime.time())
    print(datetime_obj)
    Output:

    2023-07-25 00:00:00

Python Date to DateTime Object Example
-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author Info:

Rakesh (He/Him) is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap