I need to convert time from list of dictionaries, that I made from json file, to date time format the json file looks like this
{"name": "Thomas", "time_created": 1665070563, "gender": null}
{"name": "Lisa", "time_created": 1665226717, "gender": "female", "age": 59}
{"name": "James", "time_created": 1664913997, "gender": "male", "last_name": "Rogers"}
{"name": "Helen", "time_created": 1664651357, "gender": "female", "last_name": "Scott"}
{"name": "Nora", "time_created": 1664689732, "gender": "female", "age": null}
I try to write this code
import jsonlines
import datetime
with jsonlines.open('data.jsonl', 'r') as jsonl_f:
lst = [obj for obj in jsonl_f]
for value_man in lst:
for value in value_man.keys():
value['time_created'] = datetime.datetime.fromtimestamp(value['time_created'])
print(lst)
but I have a error here
value['time_created'] = str(datetime.datetime.fromtimestamp(value['time_created'])) TypeError: string indices must be integers
CodePudding user response:
You don't need to iterate over all the keys in each dict; the keys are strings, which is why the extra level of iteration is giving you a string instead of the actual dict. Just do:
for value in lst:
value['time_created'] = datetime.datetime.fromtimestamp(value['time_created'])
You can also do this:
lst = [obj for obj in jsonl_f]
more simply as:
lst = list(jsonl_f)
CodePudding user response:
You are accessing the key of the dictionary, not the value. You have to actually access the value, something along those lines:
import jsonlines
import datetime
with jsonlines.open('data.jsonl', 'r') as jsonl_f:
lst = [obj for obj in jsonl_f]
for value_man in lst:
for value in value_man.keys():
if value == 'time_created':
value_man[value] = datetime.datetime.fromtimestamp(value_man[value])
print(lst)