Converting Datetime Objects to Date-Only Strings in Python
In Python, it's common to encounter situations where you need to convert a datetime object into a string representing only the date. For instance, you may have a datetime object like:
datetime.datetime(2012, 2, 23, 0, 0)
And you want to transform it into a string like '2/23/2012'. To achieve this, the strftime method proves to be a valuable tool.
The strftime method allows you to format your datetime object into a desired string representation. Here's an example to demonstrate its usage:
import datetime t = datetime.datetime(2012, 2, 23, 0, 0) date_string = t.strftime('%m/%d/%Y')
In this example, we've used the '%m/%d/%Y' format string. It specifies the output format as follows:
As a result, running the above code will produce the desired date-only string:
'02/23/2012'
For further customization options, you can refer to the extensive documentation provided by the Python library on formatting date and time.
The above is the detailed content of How to Convert a Python Datetime Object to a Date-Only String?. For more information, please follow other related articles on the PHP Chinese website!