4

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 Answers 3

6

from datetime import datetime
datetime.strptime('2010-10-08 14:26:01.220000'[:-7], 
                '%Y-%m-%d %H:%M:%S').strftime('%b %d %Y')
Sign up to request clarification or add additional context in comments.

Comments

2

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'

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.