Another frequent need when moving dates is to be able to move the date to the next or previous month.
If you read the Going to tomorrow recipe, you will see many similarities with this recipe even though there are some additional changes that are required when working with months that are not needed when working with days, as months have a variable duration.
Perform the following steps for this recipe:
- The
shiftmonth
function will allow us to move our date back and forth by any number of months:
import datetime def shiftmonth(d, months): for _ in range(abs(months)): if months > 0: d = d.replace(day=5) + datetime.timedelta(days=28) else: d = d.replace(day=1) - datetime.timedelta(days=1) d = d.replace(day=1, hour=0, minute=0, second=0, microsecond=0) return d
- Using it is as simple as just providing the months you want to add or remove:
>>> now = datetime.datetime.utcnow()
>>> now
datetime...