【问题标题】:Python while loop continues beyond the while conditionPython while 循环继续超出 while 条件
【发布时间】:2023-01-11 05:18:20
【问题描述】:

我的 while 循环没有按预期停止。显然,我在这里缺少一些基本的东西。

这是我的代码:

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
while start < end_final:
    ed = sd + datetime.timedelta(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(2)

它打印日期到 2262 年 4 月 10 日,然后给我错误:

 OverflowError: Python int too large to convert to C long

但是 while 循环应该在 2022 年 1 月底停止。有什么想法吗?

【问题讨论】:

  • 你打算如何让start &lt; end_final变成假的?
  • startend_final 都没有改变,所以这个陈述总是正确的
  • 可能你想要while sd &lt; end_final
  • 您更改了 sd 而不是 start 因此您只更改存储为 sd 而不是 start 的复制值因此您的 while 循环在每次迭代时检查相同的条件

标签: python date while-loop


【解决方案1】:

您正在更改 sd 变量但检查 start,尝试:

sd = start
while sd < end_final:
    # ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-16
    • 1970-01-01
    • 2012-06-24
    • 2014-03-11
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多