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

如何用SQL根据日期列表生成连续时间段的起止日期

多账户连续日期段提取方案

核心处理逻辑

  • 按账户分组整理日期数据
  • 对每个账户的日期排序后,遍历检查相邻日期的间隔
  • 当日期间隔超过1天时,拆分出当前连续段,从断点处重新计算新的起止日期

示例实现代码(Python)

假设输入为字典格式,键是账户ID,值是对应日期字符串列表:

from datetime import datetime, timedelta

def extract_continuous_periods(account_date_data):
    result = {}
    for account_id, dates in account_date_data.items():
        # 转换日期格式并排序
        sorted_dt = sorted([datetime.strptime(d, "%Y-%m-%d") for d in dates])
        periods = []
        if not sorted_dt:
            result[account_id] = periods
            continue
        
        # 初始化第一个时间段的起止
        current_start = sorted_dt[0]
        current_end = sorted_dt[0]
        
        for dt in sorted_dt[1:]:
            # 判断是否为连续日期(间隔1天)
            if dt - current_end == timedelta(days=1):
                current_end = dt
            else:
                # 保存当前连续段,重置起止点
                periods.append(f"{current_start.strftime('%Y-%m-%d')} 至 {current_end.strftime('%Y-%m-%d')}")
                current_start = dt
                current_end = dt
        # 保存最后一个连续段
        periods.append(f"{current_start.strftime('%Y-%m-%d')} 至 {current_end.strftime('%Y-%m-%d')}")
        result[account_id] = periods
    return result

# 测试用例
test_data = {
    "2376": ["2022-01-01", "2022-01-02", "2022-01-03", "2022-01-07", "2022-01-08", "2022-01-09"]
}

# 执行并输出结果
output = extract_continuous_periods(test_data)
for acc, ps in output.items():
    print(f"账户{acc}的连续日期段:")
    for i, p in enumerate(ps, 1):
        print(f"- 第{i}段:{p}")

代码执行结果

账户2376的连续日期段:
- 第1段:2022-01-01 至 2022-01-03
- 第2段:2022-01-07 至 2022-01-09

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 00:35:25