파이썬 날짜 질문 채택완료
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를 활용하면 월을 간격으로 하여 간단히 계산할 수 있어요!
</p>
<p>from datetime import date</p>
<p>from dateutil.relativedelta import relativedelta</p>
<p>import numpy as np</p>
<p> </p>
<p>def add_months(orig_date, month_count):</p>
<p> result = orig_date + relativedelta(months = month_count)</p>
<p> return result</p>
<p> </p>
<p>date = date(2018, 12, 31)</p>
<p>print('start date : ', date, '\n')</p>
<p>for j in np.arange(-14, 12):</p>
<p> print(add_months(date, j), end=' ')</p>
<p>
위 스크립트를 실행하면 정상적으로 작동하며,
그 결과는 민법 제160조(역에 의한 계산)에 부합합니다 ^^
참고로 파이썬에서의 월 계산과 관련해서 아래 문서를 참고하시면 도움이 되실 것 같네요 :)
그럼 굿밤 되세요! ^-^
답변에 대한 댓글 2개
---------------------------------------------------
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 = ' ')
-----------------------------------------------------
친절히 답변해주셔서 감사합니다^^ 실례지만 한가지만 더 여쭈어 보고싶은데.. 혹시
링크에서 처럼 현재날짜를 지정하여 입력하고 한달후를 출력하고 싶으면 위코드에 무엇을 추가하고 수정해줘야 할까요?
댓글을 작성하려면 로그인이 필요합니다.
답변을 작성하려면 로그인이 필요합니다.
로그인
그럼 편안한 저녁 되세요~ ^-^