I have a list which has a few hundred dates in it but I need to filter out only the time in the format hhmmss (no : in between so I can turn them into int later on).
The list I have so far looks like this:
list_dates = ['Fri Nov 30 15:56:43 +0000 2018', 'Fri Nov 30 15:56:44 +0000 2018', 'Fri Nov 30 15:56:45 +0000 2018', 'Fri Nov 30 15:56:46 +0000 2018', ... ]
My approach so far is:
raw_list = []
new_list = []
def ConversionStrings():
j = 0
while j < (len(list_dates)+1):
for j in list_dates:
raw_list.append((list_dates[j])[11:19])
j += 1
i = 0
while i < len(raw_list):
for i in raw_list:
item = (raw_list[i]).replace(":", "")
new_list.append(item)
i += 1
Obviously this doesn't work but I can't figure out what I am doing wrong as I am pretty new to Python. The error I get is this and its referring to the j in the for loop
TypeError: list indices must be integers or slices, not str
How can I change my code to get this output? Or is there maybe a simpler way to solve this problem?
>>> new_list = [155643, 155644, 155645, ... ]
Your issue is with this section of the code:
j = 0
while j < (len(list_dates)+1):
for j in list_dates:
raw_list.append((list_dates[j])[11:19])
j += 1
Each j in list_dates is an element of the array, not the index of a certain element. So, when you try to get the jth element of list_dates with list_dates[j], you're passing in a str as an index to the array, which doesn't make sense. You should just use another while loop like you did in the outer loop, or use for k in range(len(list_dates)) or something similar.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With