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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31796798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:33:08  来源:igfitidea点击:

Python - Convert Month Name to Integer

pythondatetime

提问by huhh hhbhb

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'

如何使用 Datetime 将“Jan”转换为整数?当我尝试 strptime 时,出现错误time data 'Jan' does not match format '%m'

采纳答案by Martijn Pieters

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

您有一个缩写的月份名称,因此请使用%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)

%mis for a numericmonth.

%m数字月份。

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:

但是,如果您只想将缩写的月份映射到数字,只需使用字典即可​​。您可以从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

回答by AndrewSmiley

Off the cuff- Did you try %b?

袖手旁观 - 你试过%b吗?

回答by BlivetWidget

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

回答by Kernel

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

您将获得第 6 个月的数字