To remove the time from a datetime object in Python, convert the datetime to a date using date().
import datetime
currentDateTime = datetime.datetime.now()
currentDateWithoutTime = currentDateTime.date()
print(currentDateTime)
print(currentDateWithoutTime)
#Output:
2022-03-05 15:33:11.283729
2022-03-05
You can also use strftime() to create a string from a datetime object without the time.
import datetime
currentDateTime = datetime.datetime.now()
currentDateWithoutTime = currentDateTime.strftime('%Y-%m-%d')
print(currentDateTime)
print(currentDateWithoutTime)
#Output:
2022-03-05 15:33:11.283729
2022-03-05
When working in Python, many times we need to create variables which represent dates and times. When creating and displaying values related to dates, sometimes we need to display the current date.
With Python, we can easily remove the time from a datetime variable.
To get rid of the time, we just need to convert the datetime to a date. To do so, use the datetime date() function.
Below is a simple example of how to get remove the time from a datetime in Python.
import datetime
currentDateTime = datetime.datetime.now()
currentDateWithoutTime = currentDateTime.date()
print(currentDateTime)
print(currentDateWithoutTime)
#Output:
2022-03-05 15:33:11.283729
2022-03-05
Using strfttime to Remove the Time from Datetime in Python
The Python strftime() function is very useful when working with date and datetime variables. strftime() accepts a string representing the format of a date and returns the date as a string in the given format.
We can use strftime() to easily remove the time from datetime variables.
For example, if you want to print out the date in the format “YYYY-MM-DD”, we pass “%Y-%m-%d” to strfttime() and no time is printed.
Below is a simple Python example of how to print the date without time using strftime().
import datetime
currentDateTime = datetime.datetime.now()
currentDateWithoutTime = currentDateTime.strftime('%Y-%m-%d')
print(currentDateTime)
print(currentDateWithoutTime)
#Output:
2022-03-05 15:33:11.283729
2022-03-05
Hopefully this article has been useful for you to learn how to use Python to remove the time from datetime variables.