Convert datetime object to a String of date only in Python

wilbev picture wilbev · May 16, 2012 · Viewed 543.2k times · Source

I see a lot on converting a date string to an datetime object in Python, but I want to go the other way.
I've got

datetime.datetime(2012, 2, 23, 0, 0)

and I would like to convert it to string like '2/23/2012'.

Answer

Levon picture Levon · May 16, 2012

You can use strftime to help you format your date.

E.g.,

import datetime
t = datetime.datetime(2012, 2, 23, 0, 0)
t.strftime('%m/%d/%Y')

will yield:

'02/23/2012'

More information about formatting see here