파이썬 날짜 질문

파이썬 날짜 질문

QA

파이썬 날짜 질문

본문

def add_months(orig_date, month_count = 1):
    while month_count > 12:
        month_count -= 12
        orig_date = add_months(orig_date, 12)
    new_year = orig_date.year
    new_month = orig_date.month + month_count
    # note: in datetime.date, months go from 1 to 12
    if new_month > 12:
        new_year += 1
        new_month -= 12
    last_day_of_month = calendar.monthrange(new_year, new_month)[1]
    new_day = min(orig_date.day, last_day_of_month)
    return orig_date.replace(year=new_year, month=new_month, day=new_day)

 

import numpy as np
#
print('start date : ', date, '\n')

for j in np.arange(-14, 12):
    print(add_months(date, j), end=' ')

 

 

start date :  2018-12-31 

---------------------------------------------------------------------------
IllegalMonthError                         Traceback (most recent call last)
<ipython-input-7-61852458bd1d> in <module>
      5 
      6 for j in np.arange(-14, 12):
----> 7     print(add_months(date, j), end=' ')

<ipython-input-6-99950c2ac6b3> in add_months(orig_date, month_count)
     11         new_month -= 12
     12 
---> 13     last_day_of_month = calendar.monthrange(new_year, new_month)[1]
     14     new_day = min(orig_date.day, last_day_of_month)
     15 

C:\Anaconda3\lib\calendar.py in monthrange(year, month)
    122        year, month."""
    123     if not 1 <= month <= 12:
--> 124         raise IllegalMonthError(month)
    125     day1 = weekday(year, month, 1)
    126     ndays = mdays[month] + (month == February and isleap(year))

IllegalMonthError: bad month number -2; must be 1-12

 

 

위의 코드를 작성하여 아래와 같은 에러가 나왔습니다 

코드를 어떻게 수정하면 좋을까요?

이 질문에 댓글 쓰기 :

답변 1

안녕하세요?

 

위와 같은 에러의 발생 원인은 calendar.monthrange()가 1~12의 정수값 중 하나를 파라미터로 하는데,

 

-2가 대입되었기 때문입니다 ㅠㅠ

 

해당 월이 총 며칠인지를 구하는 메서드이기 때문에 음수값이 대입될 수 없겠죠~

 

 

제가 질문의 취지를 제대로 이해했는지 모르겠지만...

 

위 스크립트로 구하고 싶으신 결과가 2018. 12. 31.을 기준으로 하여

 

그 전후 1개월 간격의 날짜를 출력하시는 것인지요? ^-^

 

 

아쉽게도 파이썬의 datetime 모듈은 timedelta(months=n)이라는 기능을 지원하지 않기 때문에 

 

월(月)을 간격으로 하여 계산하는 것이 다소 까다롭습니다 ㅠㅠ

 

대신에 dateutil.relativedelta를 활용하면 월을 간격으로 하여 간단히 계산할 수 있어요!

 

 


from datetime import date
from dateutil.relativedelta import relativedelta
import numpy as np
 
def add_months(orig_date, month_count):
    result = orig_date + relativedelta(months = month_count)
    return result
 
date = date(2018, 12, 31)
print('start date : ', date, '\n')
for j in np.arange(-14, 12):
    print(add_months(date, j), end=' ')

 

위 스크립트를 실행하면 정상적으로 작동하며, 

 

그 결과는 민법 제160조(역에 의한 계산)에 부합합니다 ^^

 

 

참고로 파이썬에서의 월 계산과 관련해서 아래 문서를 참고하시면 도움이 되실 것 같네요 :)

 

https://stackoverflow.com/questions/4130922/how-to-increment-datetime-by-custom-months-in-python-without-using-library

 

그럼 굿밤 되세요! ^-^

 

https://stackoverflow.com/questions/546321/how-do-i-calculate-the-date-six-months-from-the-current-date-using-the-datetime?page=2&tab=votes#tab-top

 

---------------------------------------------------

from datetime import date

 

def after_month(given_date, month):

    yyyy = int(((given_date.year * 12 + given_date.month) + month)/12)

    mm = int(((given_date.year * 12 + given_date.month) + month)%12)

 

    if mm == 0:

        yyyy -= 1

        mm = 12

    return given_date.replace(year=yyyy, month=mm)

 

 print(next_date, end = ' ')

-----------------------------------------------------
친절히 답변해주셔서 감사합니다^^ 실례지만 한가지만 더 여쭈어 보고싶은데.. 혹시
링크에서 처럼 현재날짜를 지정하여 입력하고 한달후를 출력하고 싶으면 위코드에 무엇을 추가하고 수정해줘야 할까요?

답변을 작성하시기 전에 로그인 해주세요.
전체 123,127 | RSS
QA 내용 검색

회원로그인

(주)에스아이알소프트 / 대표:홍석명 / (06211) 서울특별시 강남구 역삼동 707-34 한신인터밸리24 서관 1404호 / E-Mail: admin@sir.kr
사업자등록번호: 217-81-36347 / 통신판매업신고번호:2014-서울강남-02098호 / 개인정보보호책임자:김민섭(minsup@sir.kr)
© SIRSOFT