Appearance
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:
Convert a datetime to a date object in Python using the date method
python
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
<div class="alert alert-info flex not-prose">Watch a video course Python - The Practical Guide
</div>
Alternatively, you can also use the strftime() method and the %Y-%m-%d format to extract the date from a datetime object.
Extract a date string from a datetime object in Python using the strftime method
python
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.
Parse a string of date and time and make a datetime object in Python
python
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