The first thing to do is to create the add_months function that adds months, since date or datetime handles these amounts, so we use calendar. Then we create the rangeMonth function that iterates until the new date is greater than the date set as final.
import datetime
import calendar
def add_months(sourcedate, months):
month = sourcedate.month - 1 + months
year = int(sourcedate.year + month / 12 )
month = month % 12 + 1
day = min(sourcedate.day,calendar.monthrange(year, month)[1])
return datetime.date(year,month,day)
def rangeMonth(start, end, month):
assert start <= end
d = start
dates = [d]
while True:
d = add_months(d, 6)
if d <= end:
dates.append(d)
else:
break
return dates
start = datetime.datetime.strptime('01-01-2010', "%d-%m-%Y").date()
end = datetime.datetime.strptime('01-01-2012', "%d-%m-%Y").date()
dates = rangeMonth(start, end, 6)
for date in dates:
print(date.strftime("%d-%m-%Y"))
Output:
01-01-2010
01-07-2010
01-01-2011
01-07-2011
01-01-2012