简体   繁体   中英

Python - Getting a for loop error: IndexError: list index out of range

Im stuck with one piece of my code and i cant seem to find the answer to solve the error

I keep getting the following error message but doesn't make sense:

temp = times[i].split(', ')
IndexError: list index out of range

As context, I'm scraping a website to get information on log in dates and times, it retrieves the text version of the log in date and time so im in the middle of converting the time into a datetime object so that i can then subtract another datetime object and find out if the person was late or not

My first step is to separate by comma (,) the date and the time (both are in a single string), then convert the time into a datetime object and add an if statement at the end to confirm if the log in time is < than the start of the shift and pop the item from the list if it is true

If i were to remove the IF statement, the error goes away which is kind of strange, and if i were to reduce the list by one it also goes away

from datetime import datetime, date

times  = ['5/1/2020, 8:08:54', '5/1/2020, 10:07:09', '5/1/2020, 10:27:49', '5/1/2020, 10:53:14',
'5/1/2020, 11:57:46', '5/1/2020, 12:53:38', '5/1/2020, 2:04:52', '5/1/2020, 2:14:55']

#Analysts Shift
schedule = datetime.strptime('8:05:00', '%H:%M:%S').time()

for i in range(len(times)):
    temp = times[i].split(', ')
    a = datetime.strptime(temp[1], '%H:%M:%S').time()
    if datetime.combine(date.today(), a) < datetime.combine(date.today(), schedule):
        times.pop(i)

print(times)

change your for loop to:

for i in range(len(times)-1):

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