【问题标题】:Logging dictionaries with datetime objects without Serialization error使用没有序列化错误的日期时间对象记录字典
【发布时间】:2020-04-28 17:42:40
【问题描述】:

我正在尝试将 python 字典记录为 JSON,就像 logging.info(dict(msg="foo", data=obj)) 一样。 但是在某些情况下,obj 可能包含日期时间对象,在这些情况下我会收到 JSON 序列化错误。

是否有一种简单的方法来记录自动序列化对象(例如日期时间对象)的字典,例如让它对这些对象调用“str”函数?

【问题讨论】:

    标签: python json python-3.x logging


    【解决方案1】:

    您可以为datetime 对象定义自己的序列化程序:

    def to_json(python_object):
        if isinstance(python_object, datetime.datetime):
            return {'__class__': 'datetime.datetime',
                    '__value__': time.asctime(python_object.timetuple())}
        if isinstance(python_object, time.struct_time):
            return {'__class__': 'time.asctime',
                    '__value__': time.asctime(python_object)}
        if isinstance(python_object, bytes):
            return {'__class__': 'bytes',
                    '__value__': list(python_object)}
        raise TypeError(repr(python_object) + ' is not JSON serializable')
    
    def from_json(json_object):
        if '__class__' in json_object:
            if json_object['__class__'] == 'datetime.datetime':
                return datetime.datetime.fromtimestamp(time.mktime(time.strptime(json_object['__value__'])))
            if json_object['__class__'] == 'time.asctime':
                return time.strptime(json_object['__value__'])
            if json_object['__class__'] == 'bytes':
                return bytes(json_object['__value__'])
        return json_object
    

    然后这样称呼它:

    json.dump(entry, f, default=to_json)
    

    或用于回读

    entry = json.load(f, object_hook=from_json)
    

    【讨论】:

    • 如何使用 python 的日志记录模块?只需直接记录 JSON 字符串(而不是传递字典)?
    • @JadS 好吧,那将是我的第一选择。
    猜你喜欢
    • 1970-01-01
    • 2015-12-25
    • 2011-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    • 2014-03-03
    • 1970-01-01
    相关资源
    最近更新 更多