我正在尝试创建一个函数,该函数可以将月份数字转换为缩写的月份名称,或者将月份的缩写名称转换为月份的数字。我以为这可能是一个常见问题,但我无法在网上找到它。
我在考虑日历模块。我看到可以将月份号转换为缩写的月份名称calendar.month_abbr[num]。不过,我看不出有其他方法可以走。创建用于转换另一个方向的字典是处理此问题的最佳方法吗?还是有更好的方法将月份名称改为月份编号,反之亦然?
Answers:
使用以下calendar模块创建反向字典:
import calendar
{v: k for k,v in enumerate(calendar.month_abbr)}
在Python(2.7+)之前,您需要做
dict((v,k) for k,v in enumerate(calendar.month_abbr))
<calendar._localized_month instance at 0x0164C9E0>。David的代码的原始版本在2.6和3.1中产生语法错误-都需要()在v,k左右,并且都需要枚举calendar.month_abbr,我已对其进行了修复。
calendar.month_abbr是数组而不是字典。
纯娱乐:
from time import strptime
strptime('Feb','%b').tm_mon
list(calendar.month_name).index('January')
这是另一种方法。
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]
month_cal = dict((v,k) for v,k in zip(calendar.month_abbr[1:], range(1, 13))),然后month_cal[shortMonth]
信息来源:Python文档
要从月份名称中获取月份号,请使用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')
这是一种更全面的方法,也可以接受完整的月份名称
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
在上面表达的思想的基础上,这对于将月份名称更改为其相应的月份编号有效:
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)