You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python将两个日期间的时间段按6个月间隔拆分

实现思路

你需要的是按自然半年(每年1-6月、7-12月为一个周期)拆分日期区间,首尾区间按实际起止日期截断,具体实现可以参考以下方案:

依赖说明

如果使用dateutil库简化日期偏移计算,需要先执行安装:
pip install python-dateutil

完整实现代码

from datetime import datetime
from dateutil.relativedelta import relativedelta

def split_date_range_by_half_year(start_str, end_str):
    # 将输入的日期字符串转为date对象
    start_date = datetime.strptime(start_str, "%Y-%m-%d").date()
    end_date = datetime.strptime(end_str, "%Y-%m-%d").date()
    
    result = []
    current_start = start_date
    
    while current_start <= end_date:
        # 计算当前半年的自然结束日期
        if current_start.month <= 6:
            # 上半年结束为6月30日
            current_end = datetime(current_start.year, 6, 30).date()
        else:
            # 下半年结束为12月31日
            current_end = datetime(current_start.year, 12, 31).date()
        
        # 若当前自然半年结束日期超过总结束日期,取总结束日期截断
        if current_end > end_date:
            current_end = end_date
        
        # 转成字符串格式存入结果
        result.append([current_start.strftime("%Y-%m-%d"), current_end.strftime("%Y-%m-%d")])
        # 下一个区间的起始日期为当前结束日期+1天
        current_start = current_end + relativedelta(days=1)
    
    return result

# 测试用例
start = "2018-09-23"
end = "2020-07-13"
print(split_date_range_by_half_year(start, end))

输出结果

运行上述代码将得到你需要的输出:

[['2018-09-23', '2018-12-31'], ['2019-01-01', '2019-06-30'], ['2019-07-01', '2019-12-31'], ['2020-01-01', '2020-06-30'], ['2020-07-01', '2020-07-13']]

纯标准库实现(无需安装第三方依赖)

如果不想依赖dateutil,可以用标准库timedelta替换日期偏移逻辑:

from datetime import datetime, timedelta

def split_date_range_by_half_year(start_str, end_str):
    start_date = datetime.strptime(start_str, "%Y-%m-%d").date()
    end_date = datetime.strptime(end_str, "%Y-%m-%d").date()
    
    result = []
    current_start = start_date
    
    while current_start <= end_date:
        if current_start.month <= 6:
            current_end = datetime(current_start.year, 6, 30).date()
        else:
            current_end = datetime(current_start.year, 12, 31).date()
        
        if current_end > end_date:
            current_end = end_date
        
        result.append([current_start.strftime("%Y-%m-%d"), current_end.strftime("%Y-%m-%d")])
        current_start = current_end + timedelta(days=1)
    
    return result

内容的提问来源于stack exchange,提问作者NoName91

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 15:06:07