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

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

    You can use calendar.nextmonth (from Python 3.7).

    >>> import calendar
    >>> calendar.nextmonth(year=2019, month=6)
    (2019, 7)
    >>> calendar.nextmonth(year=2019, month=12)
    (2020, 1)
    

    But be aware that this function isn't meant to be public API, it's used internally in calendar.Calendar.itermonthdays3() method. That's why it doesn't check the given month value:

    >>> calendar.nextmonth(year=2019, month=60)
    (2019, 61)
    

    In Python 3.8 is already implemented as internal function.

提交回复
热议问题