简体   繁体   中英

Python while loop continues beyond the while condition

My while loop doesn't stop when it's supposed to. Obviously there's something fundamental I'm missing here.

Here is my code:

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)

which prints dates until the 10th of April 2262 and then gives me the error:

 OverflowError: Python int too large to convert to C long

But the while loop should stop at the end of January 2022. Any ideas?

You are changing sd variable but checking the start , try:

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

when you're in a "while loop" you must add a stop indicator, like a flag, condition, or break statement.

here's an idea to break the looping close to january 2022.

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

However, the ending date it's not 31/january/2022, because you're adding the period = 5, so in that case try with "if" statements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM