Python while循环在while条件之后继续



我的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月底停止。什么好主意吗?

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

sd = start
while sd < end_final:
# ...
当你在"while循环"必须添加停止指示符,如标志、条件或中断语句。

这里有一个想法来打破循环接近2022年1月。

period = 5
start = pd.to_datetime('2022-01-01')
end_final = pd.to_datetime('2022-01-31')
sd = start
flag = True
while flag:
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)
if sd >= end_final:
flag = False

但是,结束日期不是31/january/2022,因为您添加了句点= 5,所以在这种情况下尝试使用"if"语句。

最新更新