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

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

    from datetime import timedelta
    try:
        next_month = (x.replace(day=28) + timedelta(days=7)).replace(day=x.day)
    except ValueError:  # assuming January 31 should return last day of February.
        next_month = (x + timedelta(days=31)).replace(day=1) - timedelta(days=1)
    

提交回复
热议问题