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

前端 未结 9 1829
误落风尘
误落风尘 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:06
    import calendar, datetime
    
    def next_month ( date ):
        """return a date one month in advance of 'date'. 
        If the next month has fewer days then the current date's month, this will return an
        early date in the following month."""
        return date + datetime.timedelta(days=calendar.monthrange(date.year,date.month)[1])
    
    0 讨论(0)
  • 2021-01-31 08:07
    from calendar import mdays
    from datetime import datetime, timedelta
    
    today = datetime.now()
    next_month_of_today = today + timedelta(mdays[today.month])
    

    I don't want to import dateutil. Have a try this. Good luck.

    0 讨论(0)
  • 2021-01-31 08:08

    Use dateutil module. It has relative time deltas:

    import datetime
    from dateutil import relativedelta
    nextmonth = datetime.date.today() + relativedelta.relativedelta(months=1)
    

    Beautiful.

    0 讨论(0)
提交回复
热议问题