-1

enter image description here The code I wrote above works fine except I want the numerical day (%d) of the month to stay unchanged (30th) for all the months bar February (28th). The fact that the day value remains 28 after the month February is causing my 'while' loop condition to do one more iteration because the value of 'open_date' will not equal the 'maturity date' as a result of the day value changing from 30 to 28. The 'while' loop condition becomes (2026-06-28 < 2026-06-30) when it was supposed to be (2026-06-30 < 2026-06-30) at which point it evaluates to 'False' and the date 2026-06-30 would be the last item in the list as intended. So how can I use the 'relativedelta' function to only increment the month without affecting the day?

hareko
  • 5
  • 2
  • 1
    maybe this helps, there seems to be a difference between `month` and `months`: https://stackoverflow.com/questions/9594282/how-do-you-add-3-months-to-a-datetime-date-object-in-python – 3dSpatialUser Aug 24 '22 at 06:12
  • always put code, data and full error message as text (not screenshot, not link) in question (not in comment). It will be more readable and easier to use in answer (simpler to select and copy), and more people will see it - so more people can help you. – furas Aug 24 '22 at 09:05

1 Answers1

0

Documentation for relativedelta shows also day= to set day (don't use days= which add days)

   .relativedelta(months=1, day=30)

Minimal working code

import datetime
import dateutil.relativedelta

date = datetime.date.today()

print('today:', date)

for x in range(12):
    date += dateutil.relativedelta.relativedelta(months=1, day=30)
    print(date)

Result:

today: 2022-08-24

2022-09-30
2022-10-30
2022-11-30
2022-12-30
2023-01-30
2023-02-28
2023-03-30
2023-04-30
2023-05-30
2023-06-30
2023-07-30
2023-08-30

Eventually you should use original date and add months=1, months=2, etc.

date = datetime.date.today().replace(day=30)

for x in range(12):
    new_date = date + dateutil.relativedelta.relativedelta(months=x)
    print(new_date)
furas
  • 134,197
  • 12
  • 106
  • 148