如何映射月名到月号,反之亦然?

我正在尝试创建一个函数,可以转换为一个月数字缩写的月名称或缩写的月名称,以一个月的数字。我想这可能是一个常见的问题,但我无法在网上找到它。

我在想 日历模块。我看到从月号转换成缩写的月名你可以只做 calendar.month_abbr[num]。不过,我看不出有什么办法可以改变这种状况。创建一个转换其他方向的字典是处理这个问题的最佳方法吗?或者有没有更好的方法从月名到月号,反之亦然?

206657 次浏览

使用 calendar模块创建一个反向字典(与任何模块一样,需要导入该模块) :

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

在2.7之前的 Python 版本中,由于该语言不支持 dict 理解语法,因此必须这样做

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

只是为了好玩:

from time import strptime


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

还有另一种方法。

def 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]

使用 日历模块:

数字缩写 calendar.month_abbr[month_number]

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

还有一件事:

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

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

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

信息来源: 巨蟒文档

使用 datetime 模块从月名获取月号

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

基于上述想法,这对于将月份名称更改为适当的月号是有效的:

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

您可以使用以下内容作为替代。

  1. 每月编号:

from time import strptime

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

  1. 每月编号:

import calendar

calendar.month_abbr[2]calendar.month[2]

要从月号中获取完整的日历名称,可以使用 calendar.month _ name。有关详细信息,请参阅文档: https://docs.python.org/2/library/calendar.html

month_no = 1
month = calendar.month_name[month_no]


# month provides "January":
print(month)




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

如果您不想导入日历库,并且需要一些更健壮的东西——您可以使您的代码比所提供的其他一些解决方案多一点 对不一致的文本输入更加动态。你可以:

  1. 创建 month_to_number字典
  2. 循环遍历该字典的 .items(),并检查字符串 s的小写字母是否为小写键 k

month_to_number = {
'January' : 1,
'February' : 2,
'March' : 3,
'April' : 4,
'May' : 5,
'June' : 6,
'July' : 7,
'August' : 8,
'September' : 9,
'October' : 10,
'November' : 11,
'December' : 12}


s = 'jun'
[v for k, v in month_to_number.items() if s.lower() in k.lower()][0]


Out[1]: 6

同样,如果您使用列表 l而不是字符串,则可以添加另一个 for来遍历列表。我创建的列表的值不一致,但是输出仍然是正确的月份号所需要的:

l = ['January', 'february', 'mar', 'Apr', 'MAY', 'JUne', 'july']
[v for k, v in month_to_number.items() for m in l if m.lower() in k.lower()]


Out[2]: [1, 2, 3, 4, 5, 6, 7]

我在这里的用例是,我使用 Selenium从一个网站通过自动选择一个下拉值基于一些条件的数据刮。无论如何,这需要我依靠一些数据,我相信我们的供应商是手动输入标题每个月,我不想回到我的代码,如果他们格式稍微不同,他们已经做了历史。

全月名称至月号(例如 一月二月等) :

import datetime


month_name = 'January'
month_num = datetime.datetime.strptime(month_name, '%B').month


print(month_num, type(month_num))


>> 1 <class 'int'>

部分月名至月号(例如 二月等) :

import datetime


month_name = 'Feb'
month_num = datetime.datetime.strptime(month_name, '%b').month


print(month_num, type(month_num))


>> 2 <class 'int'>

你也可以把它格式化为两位数字:

month_num = 3
formatted = f"{month_num:02}"


print(formatted, type(formatted))


>> 03 <class 'str'>

从月号到月名(或者是双位数字表示,或者是字符串或者是整数)(例如,01年1,等等) :

import datetime


month_num = '04'  # month_num = 4 will work too
month_name = datetime.datetime(1, int(month_num), 1).strftime("%B")


print(month_name)


>> April

月号到部分月名(或者是双位数字表示,或者是字符串或者是整数)(例如 01年1,等等) :

import datetime


month_num = 5  # month_num = '05' will work too
month_name = datetime.datetime(1, int(month_num), 1).strftime("%b")


print(month_name)


>> May

你可以试试:

pd.to_datetime(df['month'], format='%b').dt.month