Python - Convert Month Name to Integer

2020-08-13 06:03发布

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'

4条回答
我想做一个坏孩纸
2楼-- · 2020-08-13 06:37
from calendar import month_abbr
month = "Jun"
for k, v in enumerate(month_abbr):
    if v == month:
        month = k
        break
print(month)

6

You will get the number of month 6

查看更多
聊天终结者
3楼-- · 2020-08-13 06:41

This is straightforward enough that you could consider just using a dictionary, then you have fewer dependencies anyway.

months = dict(Jan=1, Feb=2, Mar=3, ...)
print(months['Jan'])
>>> 1
查看更多
孤傲高冷的网名
4楼-- · 2020-08-13 06:55

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 is for a numeric month.

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}

Demo:

>>> 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
查看更多
\"骚年 ilove
5楼-- · 2020-08-13 07:01

Off the cuff- Did you try %b?

查看更多
登录 后发表回答