Last active
August 12, 2022 00:07
-
-
Save anselmobd/40168cad651aac64a0b9268e6f1b6bf4 to your computer and use it in GitHub Desktop.
Increment and decrement month of date in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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