파이썬에서 월 이름을 월 번호로 또는 그 반대로


95

월 숫자를 축약 된 월 이름으로 변환하거나 축약 된 월 이름을 월 숫자로 변환 할 수있는 함수를 만들려고합니다. 나는 이것이 일반적인 질문이라고 생각했지만 온라인에서 찾을 수 없었습니다.

달력 모듈 에 대해 생각하고있었습니다 . 월 번호를 축약 된 월 이름으로 변환하려면 그냥 할 수 있습니다 calendar.month_abbr[num]. 그래도 다른 방향으로 갈 길은 보이지 않습니다. 다른 방향으로 변환하기위한 사전을 만드는 것이이를 처리하는 가장 좋은 방법일까요? 아니면 월 이름에서 월 번호로 또는 그 반대로 이동하는 더 좋은 방법이 있습니까?

답변:


97

calendar모듈을 사용하여 역방향 사전을 만듭니다 (다른 모듈과 마찬가지로 가져와야합니다).

{month: index for index, month in enumerate(calendar.month_abbr) if month}

2.7 이전의 Python 버전에서는 dict 이해 구문이 언어에서 지원되지 않기 때문에 다음을 수행해야합니다.

dict((month, index) for index, month in enumerate(calendar.month_abbr) if month)

76

재미로:

from time import strptime

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

3
로케일에 따라 다릅니 까?
Janus Troelsen 2015

파이썬 2.7 | ValueError : 시간 데이터 'Fev'가 '% b'형식과 일치하지 않음
Diego Vinícius

@ DiegoVinícius는 'Fev'가 '2 월'이 될 것이라고 확신합니다.
Fawwaz Yusran

단지 @FawwazYusran 디에고 로케일 언어를하려고했으나 명령은 영어 월 이름을 위해 일하고있다
파이썬

이것은 루프에서 사용하는 경우 매우 비효율적입니다.
Mr. Lance E Sloan

55

달력 모듈 사용 :

Number-to-Abbr calendar.month_abbr[month_number]

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


예 : list (calendar.month_abbr) .index ( 'Feb') 결과 : 2
kibitzforu

전체 월 이름 사용 :list(calendar.month_name).index('January')
Paul

나쁘지는 않지만 여러 달 이름을 찾기 위해 루프에서 사용되는 경우별로 효율적이지 않습니다.
Mr. Lance E Sloan

22

여기에 또 다른 방법이 있습니다.

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]
매트 W.에게

3
그것은 좋은 방법입니다. 내가 제안한 방식에는 import 문이 필요하지 않습니다. 그것은 선호도의 문제입니다.
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')

15

다음은 전체 월 이름도 허용 할 수있는보다 포괄적 인 방법입니다.

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

8

하나 더:

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

0

위에 표현 된 아이디어를 바탕으로 월 이름을 적절한 월 번호로 변경하는 데 효과적입니다.

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

아니요, 다시 보면 첫 글자 단어 [0]가 대문자로 사용되고 다음 두 글자 인 word [1 : 3]에 연결되어 있음을 알 수 있습니다. 내가 게시 한 코드는 월 단어를 적절한 월 번호로 변환하는 데 정말 훌륭하게 작동합니다.
thescoop


-1
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

-1

아래에서 대안으로 사용할 수 있습니다.

  1. 월별 번호 :

from time import strptime

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

  1. 월 번호 :

import calendar

calendar.month_abbr[2] 또는 calendar.month[2]

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.