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

前端 未结 9 1832
误落风尘
误落风尘 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 08:01

    This is how I solved it.

    from datetime import date
    try:
        (year, month) = divmod(date.today().month, 12)
        next_month = date.today().replace(year=date.today().year+year, month=month+1)
    except ValueError:
        # This day does not exist in next month
    

    You can skip the try/catch if you only want the first day in next month by setting replace(year=date.today().year+year, month=month, day=1). This will always be a valid date since we have caught the month overflow using divmod.

提交回复
热议问题