How To Convert Date Into Datetime In Python

In this tutorial, we will learn how to convert a date object into a datetime object in Python. Date objects only hold date-related information (year, month, day), while datetime objects represent time as well (hours, minutes, seconds).

Converting a date into a datetime can be especially helpful in cases where you need to perform operations involving both dates and times, such as calculating time differences or sorting events by both date and time. We will be using the datetime module available in Python’s standard library for this conversion.

Step 1: Import the required modules

We need to import the date and datetime classes from the datetime module. You can do this using the following code:

Step 2: Create a date object

Let’s create a simple date object to represent September 15, 2021. You can do this using the date() constructor, which takes three arguments – year, month, and day – in that order:

This code will output:

2021-09-15

Step 3: Convert the date object into a datetime object

Now it’s time to convert the date object into a datetime object. We can use the datetime.combine() method for this. The method takes two arguments: the first one is the date we want to convert, and the second one is an optional time object representing the time of the day (default is midnight). Since datetime is a subclass of date, the conversion keeps the date information and extends it with time information.

Here, we will convert the date object we created in step 2 into a datetime object with the time set to midnight (default is midnight, so no need to include it as an argument):

This code will output:

2021-09-15 00:00:00

Alternatively, if you want to specify a particular time, you can import the time class and use it as follows:

This code will output:

2021-09-15 11:30:00

Full Code Example

Here’s the full code for the example:

This will output:

2021-09-15
2021-09-15 00:00:00
2021-09-15 11:30:00

Conclusion

In this tutorial, we learned how to convert a date object into a datetime object in Python using the datetime.combine() method. This simple conversion technique can be very useful for performing calculations or comparisons involving both dates and times.