我正在尝试创建一个函数,可以将月份数字转换为缩写的月份名称或将缩写的月份名称转换为月份数字。我认为这可能是一个常见的问题,但我在网上找不到相关内容。
我想使用 calendar 模块。我发现将月份数字转换为缩写的月份名称很简单,只需使用 calendar.month_abbr[num]
即可。但我没有看到相应的逆向转换方式。是否创建一个字典来进行双向转换是处理此问题的最佳方式?或者有更好的方法来实现从月份名称到月份数字的转换吗?
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)
只是为了好玩:
from time import strptime
strptime('Feb','%b').tm_mon
使用 calendar 模块:
数字到缩写:
calendar.month_abbr[month_number]
缩写到数字:
list(calendar.month_abbr).index(month_abbr)
list(calendar.month_name).index('January')
。 - Paul这是另一种实现它的方法。
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]
month_cal = dict((v,k) for v,k in zip(calendar.month_abbr[1:], range(1, 13)))
,然后使用 month_cal[shortMonth]
。 - Matt W.信息来源: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
将完整月份名称转换为月份数字(例如一月,二月等):
import datetime
month_name = 'January'
month_num = datetime.datetime.strptime(month_name, '%B').month
print(month_num, type(month_num))
>> 1 <class 'int'>
将部分月份名称转换为月份数字(例如,Jan,Feb等):
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
datetime.datetime.strptime(month_name[:3], '%b').month
。 - Mattindex
方法。月份名称的索引将对应于月份的数字。list(calendar.month_abbr).index('Jan') # returns 1
calendar.month_abbr[1]
的相反操作。month_no = 1
month = calendar.month_name[month_no]
# month provides "January":
print(month)