Source From Here
Question
I need to increment the month of a datetime value. I wanted to use timedelta, but it doesn't take month argument. There is relativedelta python package, but i don't want to install it just only for this. Also there is a solution usingstrtotime. Below is the example usage:
Does anyone have any good and simple solution besides above approaches?
How-To
Based on your comment of dates being needed to be rounded down if there are fewer days in the next month, here is a solution:
- demo.py
Execution result:
Question
I need to increment the month of a datetime value. I wanted to use timedelta, but it doesn't take month argument. There is relativedelta python package, but i don't want to install it just only for this. Also there is a solution usingstrtotime. Below is the example usage:
Does anyone have any good and simple solution besides above approaches?
How-To
Based on your comment of dates being needed to be rounded down if there are fewer days in the next month, here is a solution:
- demo.py
- #!/usr/bin/env python
- import datetime
- import calendar
- def add_months(sourcedate,months):
- month = sourcedate.month - 1 + months
- year = int(sourcedate.year + month / 12 )
- month = month % 12 + 1
- day = min(sourcedate.day,calendar.monthrange(year,month)[1])
- return datetime.date(year,month,day)
- somedate = datetime.date.today()
- print('Today = %s' % somedate)
- print('Add one month from today = %s' % add_months(somedate,1))
- print('Add 23 Months from today = %s' % add_months(somedate,23))
- otherdate = datetime.date(2010,10,31)
- print('Add one month from %s = %s' % (otherdate, add_months(otherdate,1)))
沒有留言:
張貼留言