Home >Backend Development >Python Tutorial >How to Format a DateTime Object as a Specific Date String in Python?
Convert DateTime Object to Specific Date String Format in Python
In Python, you can effortlessly convert a datetime object into a string representing the date component only. This can prove useful in various scenarios. Consider the following datetime object:
datetime.datetime(2012, 2, 23, 0, 0)
Our goal is to transform this object into a string in the format '2/23/2012'. The solution lies in employing the strftime() method to format the date according to our desired specifications.
import datetime t = datetime.datetime(2012, 2, 23, 0, 0) t.strftime('%m/%d/%Y')
By specifying the '%m/%d/%Y' format string, we instruct strftime() to generate a string representing the date in the MM/DD/YYYY format, resulting in the desired output:
'02/23/2012'
If you need to explore additional formatting options, consult the official documentation for more detailed information on strftime().
The above is the detailed content of How to Format a DateTime Object as a Specific Date String in Python?. For more information, please follow other related articles on the PHP Chinese website!