Python: How to convert datetime format?

Question:

Possible Duplicate:
How to convert a time to a string

I have a variable as shown in the below code.

a = "2011-06-09"

Using python, how to convert it to the following format?

"Jun 09,2011"
Asked By: Rajeev

||

Answers:

>>> import datetime
>>> d = datetime.datetime.strptime('2011-06-09', '%Y-%m-%d')
>>> d.strftime('%b %d,%Y')
'Jun 09,2011'

In pre-2.5 Python, you can replace datetime.strptime with time.strptime, like so (untested): datetime.datetime(*(time.strptime('2011-06-09', '%Y-%m-%d')[0:6]))

Answered By: NPE

@Tim’s answer only does half the work — that gets it into a datetime.datetime object.

To get it into the string format you require, you use datetime.strftime:

print(datetime.strftime('%b %d,%Y'))
Answered By: mgiuca
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.