月份名称到月份数字,反之亦然

我试图创build一个函数,可以将一个月份号码转换为一个缩写月份名称或一个缩写月份名称为一个月份号码。 我认为这可能是一个常见的问题,但我不能在网上find它。

我正在考虑日历模块。 我看到要从月份号码转换为缩写月份名称,你可以做calendar.month_abbr[num] 。 我看不出去另一个方向。 创build一个字典转换其他方向是处理这个最好的方法? 还是有更好的方法,从月份名称到月份号码,反之亦然?

创build一个反向字典将是一个合理的方法来做到这一点,因为它非常简单:

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

或者在支持字典理解的Python(2.7+)的最新版本中:

 {v: k for k,v in enumerate(calendar.month_abbr)} 

只是为了好玩:

 from time import strptime strptime('Feb','%b').tm_mon 

使用日历模块:

Number-to-Abbr calendar.month_abbr[month_number]

缩小到数字list(calendar.month_abbr).index(month_abbr)

这是另一种方法。

 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] 

这是一个更全面的方法,也可以接受完整的月份名称

 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') 

例:

 >>> month_string_to_number("October") 10 >>> month_string_to_number("oct") 10 

多一个:

 def month_converter(month): months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] return months.index(month) + 1 

信息来源: Python Docs

从月份名称获取月份编号使用date时间模块

 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') 

要使用月份号获取月份名称,您可以使用time

 import time mn = 11 print time.strftime('%B', time.struct_time((0, mn, 0,)+(0,)*6)) 'November'