Transform datetime Object to Date & Vice Versa in Python (2 Examples)

This post explains how to convert a datetime object to a date and vice versa in Python.

Creating Example Data & Loading datetime Module

We can load the datetime module as shown below.

from datetime import datetime

Now we generate a datetime object containing the actual date:

datetime_x = datetime.now()
print(datetime_x)
# 2022-03-15 15:37:21.140526

Example 1: Transform datetime Object into Date

As you can see above, the example date is the 15th of March 2022 at 15:37:21 pm.

In the following Python code, you can see how to extract only the date from this datetime object by using the date() function:

date_x = datetime.date(datetime_x)
print(date_x)
# 2022-03-15

A new data object called date_x has been created, which contains only the datetime.

Example 2: Transform date Object into datetime

The other way around, to combine a date and time object into a datetime object, is shown in the next example.

With the following example date:

date_x2 = datetime(2022, 8, 12, 14, 55).date()
print(date_x2)
# 2022-08-12

and example time:

time_x2 = datetime(2022, 8, 12, 14, 55).time()
print(time_x2)
# 14:55:00

To combine these two data objects into a datetime object, we can use the combine() function of the datetime module:

datetime_x2 = datetime.combine(date_x2, time_x2)
print(datetime_x2)
# 2022-10-17 14:55:00

 

Further Resources

Please find some related tutorials below.

 

Matthias Bäuerlen Python Programmer

Note: This article was created in collaboration with Matthias Bäuerlen. Matthias is a programmer who helps to create tutorials on the Python programming language. You might find more info about Matthias and his other articles on his profile page.

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top