To convert a datetime object to a string of date only in Python, you can use the strftime method.
Here’s an example:
from datetime import datetime
Create a datetime object
dt = datetime.now
Convert datetime object to a string of date only
date_str = dt.strftime(‘%Y-%m-%d’)
print(date_str)
In this example, ‘%Y-%m-%d’ is the format code for the date string. Here’s what each part of the code means:
– %Y: Four-digit year
– %m: Two-digit month (01-12)
– %d: Two-digit day of the month (00-31)
You can adjust the format code to suit your needs.
Alternatively, you can use the date method to get the date part of the datetime object, and then convert it to a string using the isoformat method:
date_str = dt.date().isoformat()
This will also give you a string in the format YYYY-MM-DD.