我有两个 YYYYmm 格式的日期
start : 202307
end : 202612
想要根据提供的间隔按间隔分割它们
例如 split_months ('202307,'202405',5)
,会给我
((202307,202311), (202312,202404), (202405,202405))
尝试使用以下代码,机器人陷入逻辑
def split_months(start, end, intv):
from datetime import datetime
periodList = []
periodRangeSplitList = []
start = datetime.strptime(start ,"%Y%m")
end = datetime.strptime(end ,"%Y%m")
mthDiff = relativedelta.relativedelta(end, start)
if mthDiff == 0:
periodRangeSplitList.append((start,start))
return periodRangeSplitList
diff = mthDiff / intv
print(diff)
for i in range(intv):
periodList.append ((start + diff * i).strftime("%Y%m"))
periodList.append(end.strftime("%Y%m"))
print(periodList)
我尝试了上面的代码,但不起作用,有人可以分享任何建议吗?
谢谢
最佳答案
使用简单的 while
循环怎么样?
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)
输出:
[('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]
示例:
# 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')]
关于python - 如何从两个间隔中获取分割月份?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77086913/