Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

month name to month number and vice versa in python

I am trying to create a function that can convert a month number to an abbreviated month name or an abbreviated month name to a month number. I thought this might be a common question but I could not find it online.

I was thinking about the calendar module. I see that to convert from month number to abbreviated month name you can just do calendar.month_abbr[num]. I do not see a way to go the other direction though. Would creating a dictionary for converting the other direction be the best way to handle this? Or is there a better way to go from month name to month number and vice versa?

like image 621
Mark_Masoul Avatar asked Aug 05 '10 18:08

Mark_Masoul


People also ask

How do you convert a month to a number in Python?

Using the strptime() function from the datetime module to convert month name to number in Python.

How do I get the full name of the month in Python?

strptime() is called. It takes month number and month format "%m" as arguments. Passing "%b" to strftime returns abbreviated month name while using "%B" returns full month name.


1 Answers

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)
like image 167
David Z Avatar answered Sep 17 '22 19:09

David Z