Python-将月份名称转换为整数

问题描述:

如何使用Datetime将 Jan转换为整数?尝试strptime时,出现错误时间数据'Jan'与格式'%m'

How can I convert 'Jan' to an integer using Datetime? When I try strptime, I get an error time data 'Jan' does not match format '%m'

您有一个缩写的月份名称,因此请使用%b

You have an abbreviated month name, so use %b:

>>> from datetime import datetime
>>> datetime.strptime('Jan', '%b')
datetime.datetime(1900, 1, 1, 0, 0)
>>> datetime.strptime('Aug', '%b')
datetime.datetime(1900, 8, 1, 0, 0)
>>> datetime.strptime('Jan 15 2015', '%b %d %Y')
datetime.datetime(2015, 1, 15, 0, 0)

%m 数字月份。

但是,如果您只想将一个缩写的月份映射到一个数字,则只需使用字典即可​​。您可以通过 calendar.month_abbr 构建一个:

However, if all you wanted to do was map an abbreviated month to a number, just use a dictionary. You can build one from calendar.month_abbr:

import calendar
abbr_to_num = {name: num for num, name in enumerate(calendar.month_abbr) if num}

演示:

>>> import calendar
>>> abbr_to_num = {name: num for num, name in enumerate(calendar.month_abbr) if num}
>>> abbr_to_num['Jan']
1
>>> abbr_to_num['Aug']
8