String to datetime

303 views Asked by At

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

3

There are 3 answers

0
knitti On BEST ANSWER

from datetime import datetime
datetime.strptime('2010-10-08 14:26:01.220000'[:-7], 
                '%Y-%m-%d %H:%M:%S').strftime('%b %d %Y')
0
mechanical_meat On

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'
0
Cameron Laird On

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.