无法更改列表中嵌套字典的数据类型



如何更改嵌套字典列表中的数据类型?

我尝试了以下代码,但一直收到一个无效的参数。

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": "kr.esat@.com", "first": "", "last": "", "role": 2, "userType": "normal", "hasLoggedIn": true, "lastLogin": 16662687523, "visitorIds": ["k.eat@cds.com"]}, "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": "kr.esat@.com", "first": "", "last": "", "role": 2, "userType": "normal", "hasLoggedIn": true, "lastLogin": 16662687523, "visitorIds": ["k.eat@cds.com"]}, "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]}

这样尝试:

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

输出

1578265850
2020-01-06 04:10:50

问题与for循环有关,在该循环中我没有将其除以1000。这是datetime.datetime.fromtimestamp的行为。为了修复它,我将脚本更改为:

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)

最新更新