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

如何按batch ID和日期分组获取批次时间区间以实现报表排序

解决方案

实现逻辑

  1. 先将所有输入的日期字符串转为可计算的日期类型,按时间倒序排序
  2. 设定批次分组的时间间隔阈值(根据示例场景可设置为180天,小于该阈值的相邻日期归为同一批次)
  3. 对每个分组的日期计算区间:单个日期的区间为日期前1天 - 当日,多个日期的区间为分组最早日期前1天 - 分组最晚日期
  4. 最后将日期转回你需要的月/日/年字符串格式输出

示例代码(Python)

from datetime import datetime, timedelta

# 输入的日期列表
date_strs = [
    "1/1/2021",
    "5/1/2021",
    "8/1/2021",
    "3/7/2020",
    "4/2/2019"
]

# 转换为datetime对象并降序排序
dates = sorted([datetime.strptime(d, "%m/%d/%Y") for d in date_strs], reverse=True)

# 按间隔阈值分组,180天可根据实际业务规则调整
batch_groups = []
current_group = [dates[0]]
for d in dates[1:]:
    if (current_group[-1] - d).days < 180:
        current_group.append(d)
    else:
        batch_groups.append(current_group)
        current_group = [d]
batch_groups.append(current_group)

# 生成时间区间
result = []
for group in batch_groups:
    max_d = max(group)
    min_d = min(group)
    start_d = min_d - timedelta(days=1)
    # 格式化去掉前缀0,匹配你需要的输出格式
    start_str = start_d.strftime("%m/%d/%Y").lstrip("0").replace("/0", "/")
    end_str = max_d.strftime("%m/%d/%Y").lstrip("0").replace("/0", "/")
    result.append(f"{start_str} - {end_str}")

# 打印输出
for line in result:
    print(line)

输出结果

8/12/2020 - 8/1/2021
3/6/2020 - 3/7/2020
4/1/2019 - 4/2/2019

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 00:15:03