Reputation: 845
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)
Upvotes: 0
Views: 283
Reputation: 1202
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)
Upvotes: 1