how to get the same day of next month of a given day in python using datetime

前端 未结 9 1988
误落风尘
误落风尘 2021-01-31 07:41

i know using datetime.timedelta i can get the date of some days away form given date

daysafter = datetime.date.today() + datetime.timedelta(days=5)
         


        
9条回答
  •  南笙
    南笙 (楼主)
    2021-01-31 07:50

    I often need to need to keep the date as last in month when adding months. I try to add the amount of months to the day after and then remove one day again. If that fails I add one more day until success.

    from datetime import timedelta
    
    DAY = timedelta(1)
    
    def add_months(d, months):
        "Add months to date and retain last day in month."
        d += DAY
        # calculate year diff and zero based month
        y, m = divmod(d.month + months - 1, 12)
        try:
            return d.replace(d.year + y, m + 1) - DAY
        except ValueError:
            # on fail return last day in month
            # can't fail on december so just adding one more month
            return d.replace(d.year + y, m + 2, 1) - DAY
    

提交回复
热议问题