Unable to change data type from nested dictionary in list

Question:

How do I change data type in a list of nested dictionary?

I have tried the following code but I keep receiving a invalid argument.

results = json.load(response)

for date in results:
    last_update = datetime.datetime.fromtimestamp(date[0]['lastUpdatedAt'])
    date[0]['lastUpdatedAt'] = last_update

print(results)

json document : 
[{"createdByUser": {"id": "15156", "username": "[email protected]", "first": "", "last": "", "role": 2, "userType": "normal", "hasLoggedIn": true, "lastLogin": 16662687523, "visitorIds": ["[email protected]"]}, "createdAt": 15735485109, "lastUpdatedByUser": {"id": "62484203008", "username": "ipres.com", "first": "I", "last": "Trs", "role": 2, "userType": "normal", "deletedAt": 1651734030, "hasLoggedIn": true, "lastLogin": 16197075936, "visitorIds": ["ipods.com", "0"]}, "lastUpdatedAt": 1578265850, "kind": "Guide", "rootVersionId": "-NXd1A-f3Iy6sOuYhycQLs", "stableVersionId": "-NXzsod1A-f3IcQLs-2028418", "appId": -323232, "appIds": [-323232], "id": "-NXzsod13I6ss", "name": "Accommodation Types", "state": "disabled", "emailState": "", "launchMethod": "auto", "isMultiStep": false, "isTraining": false]}

Here is the error: Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
KeyError: 0

Expected result: change epoch to date in lastUpdatedAt key
[{"createdByUser": {"id": "15156", "username": "[email protected]", "first": "", "last": "", "role": 2, "userType": "normal", "hasLoggedIn": true, "lastLogin": 16662687523, "visitorIds": ["[email protected]"]}, "createdAt": 15735485109, "lastUpdatedByUser": {"id": "62484203008", "username": "ipres.com", "first": "I", "last": "Trs", "role": 2, "userType": "normal", "deletedAt": 1651734030, "hasLoggedIn": true, "lastLogin": 16197075936, "visitorIds": ["ipods.com", "0"]}, ***"lastUpdatedAt": 2015-02-02***, "kind": "Guide", "rootVersionId": "-NXd1A-f3Iy6sOuYhycQLs", "stableVersionId": "-NXzsod1A-f3IcQLs-2028418", "appId": -323232, "appIds": [-323232], "id": "-NXzsod13I6ss", "name": "Accommodation Types", "state": "disabled", "emailState": "", "launchMethod": "auto", "isMultiStep": false, "isTraining": false]}

Asked By: Caroline Silva

||

Answers:

Try like this:

import datetime

print(results[0]['lastUpdatedAt'])
results[0]['lastUpdatedAt'] = datetime.datetime.fromtimestamp(results[0]['lastUpdatedAt'])
print(results[0]['lastUpdatedAt'])

Output

1578265850
2020-01-06 04:10:50
Answered By: inquirer

The issue was related to the for loop in which I did not divide it by 1000. This is the behaviour of the datetime.datetime.fromtimestamp.
To fix it, I changed the script to:

results = json.load(response)

for date in results:
    last_update = datetime.datetime.fromtimestamp((date[0]     
        ['lastUpdatedAt'])/1000).date()
    date[0]['lastUpdatedAt'] = last_update

print(results)
Answered By: Caroline Silva