[QN] How to convert month name to month number in Python
For a short script I was writing I needed to convert a string representation of the month (“month name”) into a numerical value (“month number”). A quick google led to many solutions to the inverse problem, which to me seems a lot easier. Here is a quick and dirty solution that uses the calendar module.
import calendar
list(calendar.month_name).index(month_name)
I chose to use the calendar module array month_name because I would rather not have to create a list of month names myself.
Larry Said,
July 2, 2009 @ 9:58 am
I needed to do the same thing. I had manually defined a dictionary like this: months = {‘Jan’: 1, ‘Feb’: 2…}, which worked fine, but it bugged me and I was looking for a nicer way to do it (slow day at work).
I found that when I replaced the dictionary lookup with the code snippet above, my script (which parses hundred of thousands of dated log entries) ran FIVE TIMES slower. So I took a middle approach and loaded up my dictionary like this:
months = dict([(calendar.month_abbr[index],index) for index in range(1,len(calendar.month_abbr))])
..and I am back to a dictionary lookup in my loop, and performance is back where it was. It’s more obfuscated than the simple dictionary definition that I orginally had, but is a bit less error-prone (I know that calendar spelled ‘Jun’ right), shorter, and has the dubious advantage of working with the locale.