Object of type 'datetime' is not JSON serializable問題解決


1、現象

假設你的字典是樣子的,你的value是一個datetime類型的值,這時候使用json.dump會報錯 TypeError: Object of type 'datetime' is not JSON serializable

# encoding=utf-8
import datetime
import json

if __name__ == '__main__':
    data = {"id": 13500499, "update_time": datetime.datetime(2021, 12, 21, 6, 0, 15)}
    with open("測試.json", "w") as f:
        json.dump(data, f)

image-20220121165713003

2、解決

①寫個子類,繼承json.JSONEncoder

②重寫一下default函數

③json.dump時指定cls為子類

# encoding=utf-8
import datetime
import json

from datetime import date, datetime


class LoadDatetime(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder.default(self, obj)


if __name__ == '__main__':
    data = {"id": 13500499, "update_time": datetime(2021, 12, 21, 6, 0, 15)}
    with open("測試.json", "w") as f:
        json.dump(data, f, cls=LoadDatetime)

參考 https://blog.csdn.net/IT_xiao_bai/article/details/86686014


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM