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

Python while循环未按条件终止并触发OverflowError问题求助

问题分析与解决

你的循环无法终止的核心原因是while循环的判断条件用错了变量:

你在循环里持续更新的是sd变量,但循环条件却一直检查start < end_final——而start变量从初始化后就再也没被修改过,它永远是2022-01-01,必然一直小于end_final(2022-01-31),所以循环会无限执行下去,直到日期数值超出范围触发溢出错误。

修复方案

把while循环的条件改成检查sd < end_final即可,因为sd才是你在循环里持续推进的起始日期变量:

import time
import datetime
import pandas as pd
period = 5
start = pd.to_datetime('2022-01-01')
end_final = pd.to_datetime('2022-01-31')
sd = start
# 修改判断变量为sd
while sd < end_final:
    ed = sd + datetime.timedelta(days=period)
    print('This is the start of a chunk')
    print(sd)
    print(ed)
    print('This is the end of a chunk')
    print('+*************************')
    sd = ed + datetime.timedelta(days=2)

另外补充一个小细节:datetime.timedelta的参数最好显式指定days=,虽然不传参数时默认是天数,但显式书写更清晰,避免后续混淆。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 13:20:37