Month to month and vice versa in python

I am trying to create a function that can convert the month number to the month abbreviation or the month abbreviation to the month number. I thought this might be a general question, but I could not find it on the Internet.

I was thinking about calendar . I see that to convert from the month number to the month’s abbreviated name, you can simply do calendar.month_abbr[num] . However, I see no way to go in another direction. Would creating a dictionary to transform another direction be the best way to handle this? Or is there a better way to go from month to month and vice versa?

+45
python
Aug 05 '10 at 18:44
source share
8 answers

Creating a reverse dictionary would be a smart way to do this, because it is pretty simple:

 import calendar dict((v,k) for k,v in enumerate(calendar.month_abbr)) 

or in recent versions of Python (2.7+) that support dictionary understanding:

 {v: k for k,v in enumerate(calendar.month_abbr)} 
+46
Aug 05 '10 at 18:49
source share

Just for fun:

 from time import strptime strptime('Feb','%b').tm_mon 
+50
Mar 01 '11 at 18:53
source share

Using the calendar module:

calendar.month_abbr[month_number] Number calendar.month_abbr[month_number]

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

+23
Nov 20 '14 at 9:46
source share

Here is another way to do this.

 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] 
+10
Feb 21 '14 at 15:14
source share

Here is a more complete method that can also take full month names

 def month_string_to_number(string): m = { 'jan': 1, 'feb': 2, 'mar': 3, 'apr':4, 'may':5, 'jun':6, 'jul':7, 'aug':8, 'sep':9, 'oct':10, 'nov':11, 'dec':12 } s = string.strip()[:3].lower() try: out = m[s] return out except: raise ValueError('Not a month') 

Example:

 >>> month_string_to_number("October") 10 >>> month_string_to_number("oct") 10 
+8
Nov 16 '15 at 13:05
source share

Another:

 def month_converter(month): months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] return months.index(month) + 1 
+5
Oct 23 '15 at 10:25
source share

Source of information: Python docs

To get the month number on behalf of the month, use the datetime module

 import datetime month_number = datetime.datetime.strptime(month_name, '%b').month # To get month name In [2]: datetime.datetime.strftime(datetime.datetime.now(), '%a %b %d, %Y') Out [2]: 'Thu Aug 10, 2017' # To get just the month name, %b gives abbrevated form, %B gives full month name # %b => Jan # %B => January dateteime.datetime.strftime(datetime_object, '%b') 
+1
Aug 10 '17 at 5:20
source share

To get the name of the month using the month number, you can use time :

 import time mn = 11 print time.strftime('%B', time.struct_time((0, mn, 0,)+(0,)*6)) 'November' 
0
Nov 21 '16 at 12:05
source share



All Articles