月名称到月编号,反之亦然


93

我正在尝试创建一个函数,该函数可以将月份数字转换为缩写的月份名称,或者将月份的缩写名称转换为月份的数字。我以为这可能是一个常见问题,但我无法在网上找到它。

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

Answers:


95

使用以下calendar模块创建反向字典:

import calendar

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

在Python(2.7+)之前,您需要做

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

由于某些原因,这对我不起作用,>>> d = dict(v,k对于calendar.month_abbr中的k,v),文件“ <stdin>”,第1行语法错误:如果不是唯一的参数,则必须对生成器表达式加括号
Mark_Masoul

1
嗯,我做到了,它奏效了... d = dict((v,k对于枚举中的k,v(calendar.month_abbr))
Mark_Masoul 2010年

@Mark_Masoul:什么版本的Python?看起来很旧。
S.Lott

calendar.month_abbr不是字典,而是字典<calendar._localized_month instance at 0x0164C9E0>。David的代码的原始版本在2.6和3.1中产生语法错误-都需要()在v,k左右,并且都需要枚举calendar.month_abbr,我已对其进行了修复。
韦恩·维尔纳

解决它。我应该更仔细地阅读文档,我想念的calendar.month_abbr是数组而不是字典。
David Z


53

使用日历模块:

数字到缩写 calendar.month_abbr[month_number]

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


示例:list(calendar.month_abbr).index('Feb')结果:2
kibitzforu

要使用完整的月份名称,请使用:list(calendar.month_name).index('January')
保罗

23

这是另一种方法。

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.

3
那是个好方法。我建议的方式不需要导入语句。这是一个偏好问题。
Gi0rgi0s

20

信息来源: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')

16

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

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

这个比我上面的要好
Gi0rgi0s '19


2

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

import time

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

'November'

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

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

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

1

在上面表达的思想的基础上,这对于将月份名称更改为其相应的月份编号有效:

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

也许我在误读您要做什么,但是您确定它不应该是单词[0:3]吗?
pseudoku '19

不,如果再次查看,您会发现第一个字母word [0]以大写形式使用,并与后两个字母word [1:3]串联在一起。我发布的代码可以很好地将月份字词转换为相应的月份号。
thescoop '19

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

说明您的编码总是更好
Badro Niaimi

0

您可以使用以下替代方法。

  1. 月号:

from time import strptime

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

  1. 月数:

import calendar

calendar.month_abbr[2] 要么 calendar.month[2]

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.