How do I convert a datetime to date?
You can use the date()
function from the datetime module in Python to convert a datetime object to just a date object. Here's an example:
from datetime import datetime
# Initialize a datetime object
dt = datetime(2022, 1, 16, 12, 30, 45)
# Convert to date object
date_object = dt.date()
print(date_object) # Output: 2022-01-16
Watch a video course
Python - The Practical Guide
Alternatively, you can also use the strftime()
method and the %Y-%m-%d
format to extract the date from a datetime object.
from datetime import datetime
dt = datetime(2022, 1, 16, 12, 30, 45)
date_string = dt.strftime('%Y-%m-%d')
print(date_string) # Output: '2022-01-16'
You can use the datetime.strptime()
method to parse a string of date and time and return a datetime object, and then use the date()
method to convert it to a date.
from datetime import datetime
dt_str = "2022-01-16 12:30:45"
dt = datetime.strptime(dt_str, "%Y-%m-%d %H:%M:%S")
date_object = dt.date()
print(date_object) # Output: 2022-01-16