first of all wishing all of you successful 2024 year! Im trying to create a date range sortable filter in my PySimpleGUI table app, but unfortunately im getting this error all the time:
Traceback (most recent call last):
File "c:\Python\Lib\KW-APP-FINAL.py", line 285, in <module>
filtered_td = filter_data(date_from, date_to, td)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Python\Lib\KW-APP-FINAL.py", line 46, in filter_data
date = datetime.datetime.strptime(item['Дата'], '%Y-%m-%d %H:%M:%S').date()
~~~~^^^^^^^^
TypeError: list indices must be integers or slices, not str
So any ideas how to fix that? P.S. I'm newbie in Python, sorry :)
Here is the code:
`
def filter_data(date_from, date_to, td):
filtered_td = []
for item in td:
date = datetime.datetime.strptime(item['Дата'], '%Y-%m-%d %H:%M:%S').date()
if date_from <= date <= date_to:
filtered_td.append(item)
return filtered_td`
and also in the loop:
`
elif event == 'Покажи':
date_from = values['-DATE_FROM-']
date_to = values['-DATE_TO-']
if date_from and date_to:
try:
date_from = datetime.datetime.strptime(date_from, '%Y-%m-%d %H:%M:%S').date()
date_to = datetime.datetime.strptime(date_to, '%Y-%m-%d %H:%M:%S').date()
filtered_td = filter_data(date_from, date_to, td)
window['-TABLE-'].update(values=filtered_td)
except ValueError:
sg.popup('Въвели сте неправилен формат на дата. Моля използвайте ГОДИНА-МЕСЕЦ-ДЕН!')
else:
sg.popup('Моля въведете начална и крайна дата!')
`
It is caused by that the item in td is a List and you want to index it by a string 'Дата'. Maybe it can be done by
td[Headings.index('Дата')].Example Code
You can refer following code about how to revise your code to work.