Program Club

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

proclub 2020. 10. 22. 23:42
반응형

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


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

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


리버스 딕셔너리를 만드는 것은 매우 간단하기 때문에이 작업을 수행하는 합리적인 방법이 될 것입니다.

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

또는 사전 이해를 지원하는 최신 버전의 Python (2.7+) :

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

재미로:

from time import strptime

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

달력 모듈 사용 :

Number-to-Abbr calendar.month_abbr[month_number]

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


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

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]

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

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

정보 출처 : 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')

하나 더:

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

월 번호를 사용하여 월 이름을 얻으려면 다음을 사용할 수 있습니다 time.

import time

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

'November'

위에 표현 된 아이디어를 바탕으로 이것은 효과적입니다.

from time import strptime

word = 'september'
new = word[0].upper() + word[1:3].lower()
strptime(new,'%b').tm_mon

참고 URL : https://stackoverflow.com/questions/3418050/month-name-to-month-number-and-vice-versa-in-python

반응형