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
form month name to number
d=['JAN','FEB','MAR','April','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC']
N=input()
for i in range(len(d)):
if d[i] == N:
month=(i+1)
print(month)
One more:
def month_converter(month):
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
return months.index(month) + 1
To get the full calendar name from the month number, you can use calendar.month_name. Please see the documentation for more details: https://docs.python.org/2/library/calendar.html
month_no = 1
month = calendar.month_name[month_no]
# month provides "January":
print(month)
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)
Building on ideas expressed above, This is effective for changing a month name to its appropriate month number:
from time import strptime
monthWord = 'september'
newWord = monthWord [0].upper() + monthWord [1:3].lower()
# converted to "Sep"
print(strptime(newWord,'%b').tm_mon)
# "Sep" converted to "9" by strptime
You can use below as an alternative.
from time import strptime
strptime('Feb','%b').tm_mon
import calendar
calendar.month_abbr[2]
or
calendar.month[2]