month name to month number and vice versa in python

Solution 1:

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)

Solution 2:

Just for fun:

from time import strptime

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

Solution 3:

Using calendar module:

Number-to-Abbr calendar.month_abbr[month_number]

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

Solution 4:

Here's yet another way to do it.

def monthToNum(shortMonth):
    return {
            'jan': 1,
            'feb': 2,
            'mar': 3,
            'apr': 4,
            'may': 5,
            'jun': 6,
            'jul': 7,
            'aug': 8,
            'sep': 9, 
            'oct': 10,
            'nov': 11,
            'dec': 12
    }[shortMonth]