Convert datetime Object to Date & Vice Versa in Python (2 Examples)
The table of content is structured as follows:
Let’s do this!
Example 1: Convert datetime Object into Date
This example explains how to convert a datetime object into a date.
As a first step, we have to import the datetime module into Python:
from datetime import datetime
Next, we can create a datetime object containing the current date as shown below:
my_datetime = datetime.now() print(my_datetime) # 2021-11-22 16:15:07.540406
As you can see, our example date is the 22nd of November 2021 at 4:15:07 pm.
If we now want to extract only the date from this datetime object, we can use the date() function as shown in the following Python code:
my_date = datetime.date(my_datetime) print(my_date) # 2021-11-22
The previous Python code has created a new data object called my_date, which contains only the date of our datetime object (i.e. 2021-11-22).
Example 2: Convert date Object into datetime
This example explains how to combine a date and a time object into a datetime object, i.e. the other way around compared to Example 1.
Consider the following example date…
my_date2 = datetime(2022, 10, 17, 13, 27).date() print(my_date2) # 2022-10-17
…and the following example time:
my_time2 = datetime(2022, 10, 17, 13, 27).time() print(my_time2) # 13:27:00
Now, we can combine these two data object into a datetime object using the combine() function of the datetime module:
my_datetime2 = datetime.combine(my_date2, my_time2) print(my_datetime2) # 2022-10-17 13:27:00
The output of the previous syntax is a properly formatted datetime object in Python.
Video, Further Resources & Summary
Would you like to know more on how to convert datetime objects to dates and vice versa in Python? In this case, you should have a look at the following YouTube video of the YouTube channel of Code Remedies.
The video explains how to convert strings and numbers into the datetime format:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
Furthermore, you may have a look at the other Python and datetime tutorials on this website:
- Convert datetime Object to Date Only String in Python
- Modify & Edit pandas DataFrames in Python
- Keep Only Date Part when Using pandas.to_datetime in Python
- Handling DataFrames Using the pandas Library in Python
- Python Programming Tutorials
This tutorial has shown how to switch from datetime to only date and the other way around in the Python programming language. In case you have any further questions, you may leave a comment below.
This tutorial was created in collaboration with Gottumukkala Sravan Kumar. Please have a look at Gottumukkala’s author page to get more information about his academic background and the other articles he has written for Statistics Globe.