如何将月份名称映射到月份数字,反之亦然?

151 投票
16 回答
241466 浏览
提问于 2025-04-16 02:23

我想写一个函数,可以把月份的数字转换成缩写的月份名称,或者把缩写的月份名称转换成月份的数字。我觉得这个问题应该很常见,但我在网上找不到相关的内容。

我在考虑使用calendar模块。我发现要把月份数字转换成缩写的月份名称,可以直接用calendar.month_abbr[num]。不过,我没有找到从缩写的月份名称转换回月份数字的方法。创建一个字典来处理这个转换是不是最好的办法?或者有没有更好的方法可以在月份名称和月份数字之间转换?

16 个回答

82

使用 calendar 模块:

数字转缩写 calendar.month_abbr[month_number]

缩写转数字 list(calendar.month_abbr).index(month_abbr)

95

纯粹为了好玩:

from time import strptime

strptime('Feb','%b').tm_mon
136

使用calendar模块创建一个反向字典(就像其他模块一样,你需要先导入它):

{month: index for index, month in enumerate(calendar.month_abbr) if month}

在Python 2.7之前的版本中,由于语言不支持字典推导的语法,你需要这样做:

dict((month, index) for index, month in enumerate(calendar.month_abbr) if month)

撰写回答