python and date loop

0

good, I am trying to create a vector that when entering a start and end date, dates are generated in between every 6 months and I can not do it in python :(. for example when I gave the input 01-01-2010 and 01-01-2012 I want the vector to contain:

01-01-2010

01-07-2010

01-01-2011

01-07-2011

01-01-2012

I'm doing the input with datetime. but I do not know what condition to put the For to complete an empty vector with these dates.

in advance thanks for the help.

greetings

    
asked by Richie 19.11.2017 в 06:37
source

1 answer

1

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
    
answered by 19.11.2017 / 07:19
source