views:

50

answers:

3
+3  Q: 

String to datetime

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

+4  A: 

from datetime import datetime
datetime.strptime('2010-10-08 14:26:01.220000'[:-7], 
                '%Y-%m-%d %H:%M:%S').strftime('%b %d %Y')
knitti
Thanks! works great :)
Joel
+2  A: 

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'
Adam Bernier
A: 

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.

Cameron Laird