24

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"
Jaroslav Bezděk
  • 2,697
  • 2
  • 14
  • 29
Rajeev
  • 39,163
  • 71
  • 171
  • 269
  • possible duplicate of [Parse date and format it using Python](http://stackoverflow.com/questions/2265357/parse-date-and-format-it-using-python) or [Parsing dates and times from strings using Python](http://stackoverflow.com/questions/1713594/parsing-dates-and-times-from-strings-using-python) – jscs Jun 09 '11 at 06:32
  • your quetion related to date format , Heading indicate datetime format, Connfusing! – Abdul Razak Nov 17 '20 at 12:43

2 Answers2

60
>>> 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]))

NPE
  • 438,426
  • 93
  • 887
  • 970
4

@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'))
mgiuca
  • 19,797
  • 6
  • 50
  • 70