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

前端 未结 9 1827
误落风尘
误落风尘 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

    This work for me

    import datetime
    import calendar
    
    
    def next_month_date(d):
        _year = d.year+(d.month//12)
        _month =  1 if (d.month//12) else d.month + 1
        next_month_len = calendar.monthrange(_year,_month)[1]
        next_month = d
        if d.day > next_month_len:
            next_month = next_month.replace(day=next_month_len)
        next_month = next_month.replace(year=_year, month=_month)
        return next_month
    

    usage:

    d = datetime.datetime.today()
    print next_month_date(d)
    

提交回复
热议问题