How to Combine Date and Time in Python?

Estimated read time 1 min read

To combine a date and time in Python, you can use the datetime module. The datetime module provides the datetime class, which allows you to work with dates and times together. Here’s an example:

from datetime import datetime, date, time

# Create a date object
my_date = date(2022, 5, 10)

# Create a time object
my_time = time(15, 30)

# Combine date and time into a datetime object
my_datetime = datetime.combine(my_date, my_time)


In this example, we first create a date object called my_date representing May 10, 2022. We then create a time object called my_time representing 15:30 (3:30 PM).

To combine the date and time, we use the combine() method of the datetime class. We pass the my_date and my_time objects as arguments to the combine() method, which returns a datetime object.

Finally, we print the my_datetime object, which represents the combined date and time:

2022-05-10 15:30:00

The output shows the combined date and time in the format YYYY-MM-DD HH:MM:SS.

By combining the date and time objects using the datetime module, you can work with both date and time information simultaneously.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply