Python Forum
list index out of range
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
list index out of range
#1
I am converting a list of times and dates taken from a file into european time.
The conversion function seems to do its job, but when I go and print the outcome,
i can only print the first value.
The list of original times is over 200000 values but with this new conversion,
only the first value is the one that shows.
In order for what I am saying to make sense, kindly refer to my code and its comments.
If the info I am giving are not clear/enough, please say something.
How do I fix this and make sure that this function has as many values as the original list of dates?

from astral import Astral 
from scipy import *
from pylab import*
import numpy as np
from numpy import array
import matplotlib.pyplot as plt
import datetime
from datetime import timezone
from datetime import timedelta
import matplotlib.dates as dates
import pandas as pd  
import pytz
import sys

def last_digits(num, last_digits_count=2):
    return abs(num) % (10**last_digits_count)

orig_date=[]
orig_time=[]
movements=[]

with open('bird_jan25jan16.txt', 'r') as f:
    for line in f:
        data = line.split()    # Splits on whitespace        
        orig_date.append(data[0][:])
        orig_time.append((data[1][:]))
        movements.append(int(data[2][:]))
    for i in range(0,len(orig_date)):
        if ((len(str(movements[i-1])) - len(str(movements[1]))) >=2):            
            if movements[i]==0 or (  (movements[i-1] == movements[i+1] ) and  (last_digits(movements[i-1]) == last_digits(movements[i]))):
                movements[i]=((movements[i-1]+movements[i+1])/2)

            

        


""" putting date and time together and converting them to datetime objects"""

dt_fmt = '%Y-%m-%d %H:%M:%S.%f

timestamps = []

for col_dt in zip(orig_date , orig_time):
    
    new_dt_str = ' '.join(col_dt)
    new_dt = datetime.datetime.strptime(new_dt_str, dt_fmt)
    timestamps.append(new_dt)
   

def convert_local_timezone():  #function for conversion
    converted_dates=[]
    for date in timestamps:
        local_tz = pytz.timezone('Europe/Berlin')
        local_time = date.replace(tzinfo=pytz.utc).astimezone(local_tz)
        converted_dates.append(local_time)
        return converted_dates

CEU_times=convert_local_timezone()



print(timestamps[0]) #works
print(CEU_times[0]) #works
print(CEU_times[1]) # gives the error
print(len(timestamps))  #238748
print(len(CEU_times)) # should be 238748 too but instead is 1
#print(CEU_times[0].year)
Error:
File "<ipython-input-275-389e619abf53>", line 1, in <module> runfile('C:/Users/Desktop/python ode/birds_2nd_draft.py', wdir='C:/Users/Desktop/python ode') File "C:\Users\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 668, in runfile execfile(filename, namespace) File "C:\Users\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/Desktop/python ode/birds_2nd_draft.py", line 94, in <module> print(CEU_times[1]) # gives the error IndexError: list index out of range

I hope to get some help.
Again, if additional info are needed, don't hesitate to ask.
Reply
#2
Try this. Fix is in "convert_local_timezone"
from astral import Astral 
from scipy import *
from pylab import*
import numpy as np
from numpy import array
import matplotlib.pyplot as plt
import datetime
from datetime import timezone
from datetime import timedelta
import matplotlib.dates as dates
import pandas as pd  
import pytz
import sys
 
def last_digits(num, last_digits_count=2):
    return abs(num) % (10**last_digits_count)
 
orig_date=[]
orig_time=[]
movements=[]
 
with open('bird_jan25jan16.txt', 'r') as f:
    for line in f:
        data = line.split()    # Splits on whitespace        
        orig_date.append(data[0][:])
        orig_time.append((data[1][:]))
        movements.append(int(data[2][:]))
    for i in range(0,len(orig_date)):
        if ((len(str(movements[i-1])) - len(str(movements[1]))) >=2):            
            if movements[i]==0 or (  (movements[i-1] == movements[i+1] ) and  (last_digits(movements[i-1]) == last_digits(movements[i]))):
                movements[i]=((movements[i-1]+movements[i+1])/2)
 
             
 
         
 
 
""" putting date and time together and converting them to datetime objects"""
 
dt_fmt = '%Y-%m-%d %H:%M:%S.%f
 
timestamps = []
 
for col_dt in zip(orig_date , orig_time):
     
    new_dt_str = ' '.join(col_dt)
    new_dt = datetime.datetime.strptime(new_dt_str, dt_fmt)
    timestamps.append(new_dt)
    
 
def convert_local_timezone():  #function for conversion
    converted_dates=[]
    for date in timestamps:
        local_tz = pytz.timezone('Europe/Berlin')
        local_time = date.replace(tzinfo=pytz.utc).astimezone(local_tz)
        converted_dates.append(local_time)
    return converted_dates
 
CEU_times=convert_local_timezone()
 
 
 
print(timestamps[0]) #works
print(CEU_times[0]) #works
print(CEU_times[1]) # gives the error
print(len(timestamps))  #238748
print(len(CEU_times)) # should be 238748 too but instead is 1
#print(CEU_times[0].year)
Reply
#3
thanks
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to fix list index out of range longmen 26 5,858 Apr-27-2022, 05:46 PM
Last Post: deanhystad
  list index out of range OliverG 3 2,325 Sep-03-2021, 12:04 AM
Last Post: itsmycode
  Index List a04j 2 2,910 Jul-10-2021, 01:14 PM
Last Post: BashBedlam
  List index out of range when turning CSV into dict ranbarr 15 6,401 May-12-2021, 10:38 AM
Last Post: ranbarr
  List vs index: Frederico_Caldas 5 3,577 Jul-03-2020, 10:55 AM
Last Post: DeaD_EyE
  To find the index of the first occurrence of the key in the provided list Angry_bird89 4 3,239 Jun-20-2020, 06:53 PM
Last Post: Angry_bird89
  IndexError: list index out of range abdullahali 4 3,842 Jan-17-2019, 07:54 AM
Last Post: buran
  String index out of range felie04 2 5,511 Aug-17-2018, 11:18 PM
Last Post: felie04
  Accessing data in zip - Index out of range pythoneer 24 12,717 Mar-15-2018, 06:19 PM
Last Post: buran
  "List index out of range" for output values pegn305 3 5,292 Nov-26-2017, 02:20 PM
Last Post: heiner55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020