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 commo
Information source: Python Docs
To get month number from month name use 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')
Here is a more comprehensive method that can also accept 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
def month_num2abbr(month):
month = int(month)
import calendar
months_abbr = {month: index for index, month in enumerate(calendar.month_abbr) if month}
for abbr, month_num in months_abbr.items():
if month_num==month:
return abbr
return False
print(month_num2abbr(7))
Here's yet another way to do it.
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]
Using calendar module:
Number-to-Abbr
calendar.month_abbr[month_number]
Abbr-to-Number
list(calendar.month_abbr).index(month_abbr)
Just for fun:
from time import strptime
strptime('Feb','%b').tm_mon