본문 바로가기
파이썬

파이썬 How to increment datetime by custom months in python without using library

by º기록 2020. 10. 25.
반응형

datetime 값의 월을 증가시켜야합니다.

next_month = datetime.datetime(mydate.year, mydate.month+1, 1)

월이 12 일 때 13이되고 "month must be in 1..12"라는 오류가 발생합니다. (연도가 증가 할 것으로 예상했습니다)

timedelta를 사용하고 싶었지만 월 인수가 필요하지 않습니다.



time = strtotime(str(mydate));
next_month = date("Y-m-d", strtotime("+1 month", time));

datetime에서 str, time, datetime으로 변환하고 싶지 않습니다. 따라서 여전히 라이브러리입니다.

누구든지 timedelta를 사용하는 것처럼 좋고 간단한 솔루션이 있습니까?

 

해결 방법

 

수정 -다음 달의 날짜가 더 적을 경우 반올림해야하는 날짜에 대한 의견을 바탕으로 다음과 같은 해결책이 있습니다.

import datetime
import calendar

def add_months(sourcedate, months):
    month = sourcedate.month - 1 + months
    year = sourcedate.year + month // 12
    month = month % 12 + 1
    day = min(sourcedate.day, calendar.monthrange(year,month)[1])
    return datetime.date(year, month, day)

사용:

>>> somedate = datetime.date.today()
>>> somedate
datetime.date(2010, 11, 9)
>>> add_months(somedate,1)
datetime.date(2010, 12, 9)
>>> add_months(somedate,23)
datetime.date(2012, 10, 9)
>>> otherdate = datetime.date(2010,10,31)
>>> add_months(otherdate,1)
datetime.date(2010, 11, 30)

또한 시간, 분, 초에 대해 걱정하지 않는다면 datetime 대신 date 를 사용할 수 있습니다. 시간, 분, 초가 걱정된다면 datetime 을 사용하도록 내 코드를 수정하고 소스의 시간, 분, 초를 결과로 복사해야합니다.

 

참조 페이지 https://stackoverflow.com/questions/4130922

 

 

반응형

댓글