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

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

    Of course there isn't -- if today's January 31, what would be "the same day of the next month"?! Obviously there is no right solution, since February 31 does not exist, and the datetime module does not play at "guess what the user posing this impossible problem without a right solution thinks (wrongly) is the obvious solution";-).

    I suggest:

    try:
      nextmonthdate = x.replace(month=x.month+1)
    except ValueError:
      if x.month == 12:
        nextmonthdate = x.replace(year=x.year+1, month=1)
      else:
        # next month is too short to have "same date"
        # pick your own heuristic, or re-raise the exception:
        raise
    

提交回复
热议问题