在python中分割开始和结束日期以分隔年份

时间:2017-04-01 05:23:17

标签: python date pandas

我想在此处调整代码:Given a date range how can we break it up into N contiguous sub-intervals?以分割日期范围,如下所示:

开始日期为'2015-03-20',结束日期为'2017-03-12'。我想把它分成3部分。 3年中每一年都有一个,所以我得到一个这样的列表:

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

任何pythonic的方法吗?

2 个答案:

答案 0 :(得分:2)

如果我没有误解你的意思,你可以将中年添加到-12-31-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))

结果:

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

答案 1 :(得分:0)

修改您链接的原始代码:

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)))]

输入示例:

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

main()

结果:

[['2015-03-20', '2015-11-16'], ['2015-11-17', '2016-07-14'], ['2016-07-15', '2017-03-12']]