Skip to content

Instantly share code, notes, and snippets.

@anselmobd
Last active August 12, 2022 00:07
Show Gist options
  • Save anselmobd/40168cad651aac64a0b9268e6f1b6bf4 to your computer and use it in GitHub Desktop.
Save anselmobd/40168cad651aac64a0b9268e6f1b6bf4 to your computer and use it in GitHub Desktop.
Increment and decrement month of date in python
import datetime
def inc_month(dt, months):
'''
"months" can be positive or negative
If day in new month can't be the same, it will be the the closest possible.
'''
newmonth = (((dt.month - 1) + months) % 12) + 1
newyear = dt.year + (((dt.month - 1) + months) // 12)
newday = dt.day
newdt = None
while newdt is None:
try:
newdt = datetime.date(newyear, newmonth, newday)
return newdt
except ValueError:
newday -= 1
def dec_month(dt, months):
return inc_month(dt, -months)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment