Hello,
I saved a datetime.datetime.now() as a string. Now I have a string value, i.e.
2010-10-08 14:26:01.220000
How can I convert this string to
Oct 8th 2010
?
Thanks
Hello,
I saved a datetime.datetime.now() as a string. Now I have a string value, i.e.
2010-10-08 14:26:01.220000
How can I convert this string to
Oct 8th 2010
?
Thanks
from datetime import datetime
datetime.strptime('2010-10-08 14:26:01.220000'[:-7],
'%Y-%m-%d %H:%M:%S').strftime('%b %d %Y')
You don't need to create an intermediate string.
You can go directly from a datetime
to a string with strftime()
:
>>> datetime.now().strftime('%b %d %Y')
'Oct 08 2010'
There's no one-liner way, because of your apparent requirement of the grammatical ordinal.
It appears you're using a 2.6 release of Python, or perhaps later. In such a case,
datetime.datetime.strptime("2010-10-08 14:26:01.220000", "%Y-%m-%d %H:%M:%S.%f").strftime("%b %d %Y")
comes close, yielding
Oct 08 2010
To insist on '8th' rather than '08' involves calculating the %b and %Y parts as above, and writing a decimal-to-ordinal function to intercalate between them.