使用一个简单的怎么样while
loop?
def split_months(start, end, intv):
from datetime import datetime
from dateutil import relativedelta
periodList = []
start = datetime.strptime(start, '%Y%m')
end = datetime.strptime(end, '%Y%m')
step = relativedelta.relativedelta(months=intv-1)
start_ = start
while (end_:=start_+step) <= end:
# add new period
periodList.append((start_, end_))
# update next start
start_ = end_ + relativedelta.relativedelta(months=1)
# convert output to string
return [(s.strftime('%Y%m'), e.strftime('%Y%m'))
for s, e in periodList]
split_months('202307', '202612', 5)
Output:
[('202307', '202311'),
('202312', '202404'),
('202405', '202409'),
('202410', '202502'),
('202503', '202507'),
('202508', '202512'),
('202601', '202605'),
('202606', '202610')]
如果要将最后一个间隔添加到末尾,请更改while
条件并添加额外的行 (periodList.append((start_, end))
):
def split_months(start, end, intv):
from datetime import datetime
from dateutil import relativedelta
periodList = []
start = datetime.strptime(start, '%Y%m')
end = datetime.strptime(end ,'%Y%m')
step=relativedelta.relativedelta(months=intv-1)
start_ = start
while (end_:=start_+step) < end:
periodList.append((start_, end_))
start_ = end_ + relativedelta.relativedelta(months=1)
periodList.append((start_, end))
return [(s.strftime('%Y%m'), e.strftime('%Y%m'))
for s,e in periodList]
Example:
# split_months('202307', '202612', 5)
[('202307', '202311'),
('202312', '202404'),
('202405', '202409'),
('202410', '202502'),
('202503', '202507'),
('202508', '202512'),
('202601', '202605'),
('202606', '202610'),
('202611', '202612')]
# split_months('202307', '202610', 5)
[('202307', '202311'),
('202312', '202404'),
('202405', '202409'),
('202410', '202502'),
('202503', '202507'),
('202508', '202512'),
('202601', '202605'),
('202606', '202610')]
# split_months('202307','202405',5)
[('202307', '202311'),
('202312', '202404'),
('202405', '202405')]