0

I am working with datetime to get the dates of the next two months using the following code

a               = datetime.datetime.today()  

#logic to get next two month numbers
try:
    nextmonthdate = a.replace(month=a.month+1) #a
except ValueError:
    if a.month == 12:
        nextmonthdate = a.replace(year=a.year+1, month=1)
    else:
        # next month is too short to have "same date"
        # pick your own heuristic, or re-raise the exception:
        raise

try:
    twomonthdate = a.replace(month=a.month+2)

except ValueError:
    if a.month == 12:
        twomonthdate = a.replace(year=a.year+1, month=1)
    else:
        # next month is too short to have "same date"
        # pick your own heuristic, or re-raise the exception:
        raise

I am getting the error when I try to assign the twomontdate vairable in the second try except statement. I assume its becuase its adding two to the current month (11) which would raise this error but when I print the twomonthdate it reads 2022-01-11 but the error presists.

jnord
  • 55
  • 6
  • Is [`dateutil.relateivedelta`](https://dateutil.readthedocs.io/en/stable/relativedelta.html?highlight=relativedelta#module-dateutil.relativedelta) an option? – Joshua Voskamp Nov 11 '21 at 15:35
  • Please show the exact and complete error traceback. – mkrieger1 Nov 11 '21 at 15:36
  • 1
    Does this answer your question? [How to increment datetime by custom months in python without using library](https://stackoverflow.com/questions/4130922/how-to-increment-datetime-by-custom-months-in-python-without-using-library) – Joshua Voskamp Nov 11 '21 at 15:38
  • When calculating `twomonthdate`, both November and December would cause the ValueError - but you're only checking for the case of December (and handling it incorrectly anyway, two months later is February, not January). – jasonharper Nov 11 '21 at 15:41

0 Answers0