Remove Time from datetime in Python (Example)
On this page you’ll learn how to display a datetime object without the time component in the Python programming language.
The article will contain one example for the printing of a date and time object without the time component. To be more specific, the content looks as follows:
Let’s take a look at some Python codes in action…
Example Data & Libraries
First, we have to load the datetime module:
import datetime # Load datetime
The following data is used as a basis for this tutorial:
my_datetime = datetime.datetime.today() # Create example datetime print(my_datetime) # Print example datetime # 2022-03-25 15:41:43.538029
The previous Python console output shows that our example datetime object contains the 25th of March 2022 at 3:41 pm.
Example: Display Only Date Component of datetime Object Using date() Function
This example explains how to drop the time element of a datetime object.
For this task, we can use the date function as shown in the following Python code:
my_date = my_datetime.date() # Apply date function print(my_date) # Print only date # 2022-03-25
Have a look at the previously shown output: We have removed the time of our datetime object.
Video, Further Resources & Summary
Have a look at the following video on my YouTube channel. In the video, I show the contents of the present article in Python:
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 might want to read the related tutorials that I have published on this homepage:
- Make Unaware datetime Time Zone Aware in Python
- Calculate Time Difference Between Two datetime Objects in Python
- Convert datetime to Different Time Zone in Python
- Convert Epoch Time to datetime Object & Vice Versa in Python
- Python Programming Overview
To summarize: In this tutorial, I have explained how to print a date and time object without the time component in the Python programming language. If you have further comments and/or questions on how to truncate datetime objects, please let me know in the comments section below. In addition, don’t forget to subscribe to my email newsletter in order to receive updates on the newest tutorials.
This page was created in collaboration with Matthias Bäuerlen. Have a look at Matthias’ author page to get more information about his professional background, a list of all his tutorials, as well as an overview on his other tasks on Statistics Globe.