pd441
pd441

Reputation: 2763

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?

Upvotes: 0

Views: 65

Answers (2)

Felipe Noguera P
Felipe Noguera P

Reputation: 9

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.

Upvotes: 0

Guru Stron
Guru Stron

Reputation: 141665

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

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

Upvotes: 2

Related Questions