0

For a current project, I am planning to increase the value of a calendar date by 3 months with each iteration/loop. The value for start_date should hence be [1st iteration]: 01/01/2017, [2nd interation] 01/04/2017 etc. For end_date, it should accordingly yield [1st iteration]: 31/03/2017, [2nd interation] 30/06/2017 etc.

I originally thought it would be a simple point to solve but somehow the script is not working as planned (also as many threads discuss how to increase values in one go but not how to perform this in several loops). Does anyone know how to tweak things?

The corresponding code looks as follows:

import datetime
from dateutil.relativedelta import *

for i in df.iterrows():
    start_date = '01/01/2017'
    start_date = start_date + relativedelta(months=+3)
    end_date = '31/03/2017'
    end_date = end_date + relativedelta(months=+3)

    print(start_date)
    print(end_date)

1 Answer 1

1

Your problem is that you are initialising the start_date and end_date inside the loop. Just initialise them once outside the loop, then continue process like you're doing.

import datetime
from dateutil.relativedelta import *

# year, month, day
start_date = datetime.date(2017, 1, 1)
end_date = datetime.date(2017, 3, 31)

for i in df.iterrows():
    start_date += relativedelta(months=3)
    end_date += relativedelta(months=3)

    print(start_date)
    print(end_date)
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks for this. It is yielding the error start_date = start_date + relativedelta(months=+3) - TypeError: can only concatenate str (not "relativedelta") to str though. Let me figure out how this can be solved.
See my edit. Parsing the values as dates should get the job done.
Yep, my mistake. You have to remove the zeros. Also, make sure you have the day and month in the correct order.
hmm, that's strange. Works for me. Maybe try: datetime.date.fromisoformat('2017-01-01').
Glad I helped :) Cheers.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.