month name to month number and vice versa in python

后端 未结 12 1181
情书的邮戳
情书的邮戳 2020-11-29 20:13

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

12条回答
  •  粉色の甜心
    2020-11-29 20:43

    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)
    

提交回复
热议问题