Home > Software design >  Unable to change data type from nested dictionary in list
Unable to change data type from nested dictionary in list

Time:10-23

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]}

CodePudding user response:

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

CodePudding user response:

The reason it did not was because I did not divide it by 1000. It was more related to the behaviour of the datetime.datetime.fromtimestamp

  • Related