python中的月份名称到月份编号,反之亦然
我正在尝试创建一个函数,该函数可以将月号转换为缩写的月名,或者将缩写的月名转换为月号。我想这可能是一个常见的问题,但我在网上找不到python中的月份名称到月份编号,反之亦然,python,Python,我正在尝试创建一个函数,该函数可以将月号转换为缩写的月名,或者将缩写的月名转换为月号。我想这可能是一个常见的问题,但我在网上找不到 我在考虑这个模块。我知道,要将月号转换为缩写的月名,只需执行calendar.month\u abbr[num]。但我看不到另一个方向。创建一个用于转换另一个方向的字典是处理这个问题的最佳方法吗?或者有更好的方法从月名到月号,反之亦然?使用日历模块创建反向字典(与任何模块一样,您需要导入): 在2.7之前的Python版本中,由于该语言不支持dict理解语法,因此必
我在考虑这个模块。我知道,要将月号转换为缩写的月名,只需执行
calendar.month\u abbr[num]
。但我看不到另一个方向。创建一个用于转换另一个方向的字典是处理这个问题的最佳方法吗?或者有更好的方法从月名到月号,反之亦然?使用日历
模块创建反向字典(与任何模块一样,您需要导入):
在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\u缩写[月号]
缩写为数字
列表(日历.月份缩写).索引(月份缩写)
还有一个:
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
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]
您可以使用下面的选项
从时间导入strtime
strtime('Feb','%b')。tm\u mon
导入日历
日历月\u缩写[2]
或
calendar.month[2]
要从月号中获取完整的日历名称,可以使用calendar.month\u名称。有关更多详细信息,请参阅文档:
如果您不想导入日历库,并且需要更健壮的东西,那么您可以使代码比提供的其他一些解决方案对不一致的文本输入更具动态性。你可以:
month\u to\u编号
字典.items()
,检查字符串s
的小写字母是否在小写键k
中同样,如果您有一个列表
l
,而不是一个字符串,则可以为添加另一个,以循环遍历列表。我创建的列表的值不一致,但输出仍然是正确的月数所需的值:
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
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
通过根据某些条件自动选择一个下拉值来从网站中刮取数据。无论如何,这需要我依靠一些数据,我相信我们的供应商每月都会手动输入标题,如果它们的格式与以往略有不同,我也不想回到我的代码中。这取决于您的语言环境吗?Python 2.7 | ValueError:时间数据“Fev”与格式“%b”不匹配@DiegoVinícius非常确定“Fev”应该是“Feb”。@FawwazYusran Diego尝试了语言环境,但是该命令仅适用于英语月份名称如果在循环中使用,效率会非常低。您可以这样做:month\u cal=dict((v,k)表示zip中的v,k(calendar.month\u abbr[1:],range(1,13))
,然后month\u cal[shortMonth]
这是一个好方法。我建议的方法不需要导入语句。这是一个偏好的问题。例如:list(calendar.month_abbr).index('Feb')结果:2对于完整的月份名称使用:list(calendar.month_name.).index('janur')
不错,但如果在循环中查找多个月份名称,效率就不太高了。这一个比我上面提到的好也许我误读了你的意思,但是你确定它不应该是单词[0:3]吗?不,如果你再看一遍,你会发现第一个字母单词[0]是大写的,并连接到后面的两个字母单词[1:3]。我发布的代码可以很好地将月份词转换为相应的月份号。解释您的代码总是更好的选择。感谢您抽出时间回答这个问题。由于提供的答案通常不止一个,因此当您简要描述您的解决方案的作用以及为什么它是最好的时,通常会帮助提问者。
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))
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 = ['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]