month name to month number and vice versa in python

Create a reverse dictionary using the calendar module (which, like any module, you will need to import):

{month: index for index, month in enumerate(calendar.month_abbr) if month}

In Python versions before 2.7, due to dict comprehension syntax not being supported in the language, you would have to do

dict((month, index) for index, month in enumerate(calendar.month_abbr) if month)

Just for fun:

from time import strptime

strptime('Feb','%b').tm_mon

Using calendar module:

Number-to-Abbr calendar.month_abbr[month_number]

Abbr-to-Number list(calendar.month_abbr).index(month_abbr)

Tags:

Python