0

I want to adapt the code here: Given a date range how can we break it up into N contiguous sub-intervals? to split a range of dates as follows:

Starting date is '2015-03-20' and end date is '2017-03-12'. I want to split it into 3 parts. One for each of the 3 years, so that I get a list like this:

[['2015-03-20', '2015-12-31'], ['2016-01-01', '2016-12-31'], ['2017-01-01', '2017-03-12']]

Any pythonic way to do this?

Community
  • 1
  • 1
user308827
  • 21,227
  • 87
  • 254
  • 417

2 Answers2

3

If I don't misunderstand your meaning, you can just get the middle years and append it to the string like -12-31 or -01-01.

start_date = '2015-03-20'
end_date = '2018-03-12'

def split_date(s,e):
    return [[s,s[:4]+"-12-31"]]+ [['%s-01-01'%(str(i)), '%s-12-31'%(str(i))] for i in range(int(s[:4])+1,int(e[:4]))]+[[e[:4] + "-01-01", e]]

print(split_date(start_date,end_date))

Result:

[['2015-03-20', '2015-12-31'], ['2016-01-01', '2016-12-31'], ['2017-01-01', '2017-12-31'], ['2018-01-01', '2018-03-12']]
McGrady
  • 10,869
  • 13
  • 47
  • 69
  • thanks @McGrady, this looks like what i want! Any chance, you can convert it into normal for loop, will make it easier to understand – user308827 Apr 01 '17 at 05:52
0

Modifying the original code that you linked:

from datetime import datetime, timedelta


def date_range(start, end, interval):
    start = datetime.strptime(start, "%Y%m%d")
    end = datetime.strptime(end, "%Y%m%d")
    diff = (end - start) / interval
    for i in range(interval):
        if i == 0:
            date_additive = 0
        else:
            date_additive = 1
        yield ["{0}-{1}-{2}".format(str(((start + diff * i) + timedelta(days=date_additive)).strftime("%Y").zfill(2)),
                                    str(((start + diff * i) + timedelta(days=date_additive)).strftime("%m").zfill(2)),
                                    str(((start + diff * i) + timedelta(days=date_additive)).strftime("%d").zfill(2))),
               "{0}-{1}-{2}".format(str((start + diff * (i + 1)).strftime("%Y").zfill(2)),
                                    str((start + diff * (i + 1)).strftime("%m").zfill(2)),
                                    str((start + diff * (i + 1)).strftime("%d").zfill(2)))]

Input example:

def main():
    begin = "20150320"
    end = "20170312"
    interval = 3
    print(list(date_range(begin, end, interval)))

main()

Results:

[['2015-03-20', '2015-11-16'], ['2015-11-17', '2016-07-14'], ['2016-07-15', '2017-03-12']]
MapLion
  • 1,041
  • 1
  • 12
  • 38