python中的月份名称到月份编号,反之亦然

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3418050/
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-18 10:57:16  来源:igfitidea点击:

month name to month number and vice versa in python

python

提问by Mark_Masoul

I am trying to create a function that can convert a month number to an abbreviated month name or an abbreviated month name to a month number. I thought this might be a common question but I could not find it online.

我正在尝试创建一个函数,该函数可以将月份编号转换为月份缩写名称或月份缩写名称转换为月份编号。我认为这可能是一个常见问题,但我在网上找不到。

I was thinking about the calendarmodule. I see that to convert from month number to abbreviated month name you can just do calendar.month_abbr[num]. I do not see a way to go the other direction though. Would creating a dictionary for converting the other direction be the best way to handle this? Or is there a better way to go from month name to month number and vice versa?

我在考虑日历模块。我看到要将月份数字转换为缩写的月份名称,您可以这样做calendar.month_abbr[num]。不过,我看不到另一个方向。创建用于转换另一个方向的字典是处理此问题的最佳方法吗?或者有没有更好的方法从月份名称到月份编号,反之亦然?

采纳答案by David Z

Creating a reverse dictionary would be a reasonable way to do this, because it's pretty simple:

创建一个反向字典是一个合理的方法,因为它非常简单:

import calendar
dict((v,k) for k,v in enumerate(calendar.month_abbr))

or in recent versions of Python (2.7+) which support dictionary comprehension:

或者在支持字典理解的最新版本的 Python (2.7+) 中:

{v: k for k,v in enumerate(calendar.month_abbr)}

回答by Mark Bailey

Just for fun:

只是为了好玩:

from time import strptime

strptime('Feb','%b').tm_mon

回答by Gi0rgi0s

Here's yet another way to do it.

这是另一种方法。

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]

回答by diogobernardino

Using calendarmodule:

使用日历模块:

Number-to-Abbr calendar.month_abbr[month_number]

数字到缩写 calendar.month_abbr[month_number]

Abbr-to-Number list(calendar.month_abbr).index(month_abbr)

缩写到数字 list(calendar.month_abbr).index(month_abbr)

回答by Aleksandr Aleksandrov

One more:

多一个:

def month_converter(month):
    months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    return months.index(month) + 1

回答by harryh

Here is a more comprehensive method that can also accept full month names

这里有一个更全面的方法,也可以接受完整的月份名称

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')

example:

例子:

>>> month_string_to_number("October")
10 
>>> month_string_to_number("oct")
10

回答by Kenly

To get month name using month number, you can use time:

要使用月份编号获取月份名称,您可以使用time

import time

mn = 11
print time.strftime('%B', time.struct_time((0, mn, 0,)+(0,)*6)) 

'November'

And to get month number using the month name:

并使用月份名称获取月份编号:

time.strptime("Nov", "%b").tm_mon
11
# or

time.strptime("November", "%B").tm_mon
11

回答by theBuzzyCoder

Information source: Python Docs

信息来源:Python Docs

To get month number from month name use datetime module

要从月份名称中获取月份编号,请使用 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')

回答by thescoop

Building on ideas expressed above, This is effective for changing a month name to its appropriate month number:

基于上面表达的想法,这对于将月份名称更改为其适当的月份编号是有效的:

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

回答by user12643768

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)