简体   繁体   English

使用日期时间对象记录字典而没有序列化错误

[英]Logging dictionaries with datetime objects without Serialization error

I'm trying to log python dictionary as JSON like so logging.info(dict(msg="foo", data=obj)) .我正在尝试将 python 字典记录为 JSON,就像这样logging.info(dict(msg="foo", data=obj)) However in some cases, obj may contain datetime objects and in those cases I get a JSON serialization error.但是在某些情况下, obj可能包含日期时间对象,在这些情况下我会收到 JSON 序列化错误。

Is there a simple way to log dictionaries where objects (such as datetime objects) are serialized automatically, such as having it call the "str" function on these objects?是否有一种简单的方法来记录对象(例如日期时间对象)自动序列化的字典,例如让它在这些对象上调用“str”函数?

You may define your own serializer for datetime object:您可以为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

and then call it this way:然后这样称呼它:

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

or for reading back或者为了回读

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 字典中DateTime对象的Django序列化 - Django Serialization of DateTime Objects within Dictionary 解析带和不带毫秒的日期时间对象 - Parse Datetime Objects With and Without Milleseconds 为什么python中的日期时间对象的json序列化不能用于日期时间对象的开箱即用 - Why does json serialization of datetime objects in python not work out of the box for datetime objects 构建大量对象会导致Python脚本退出而不会记录错误 - Building large array of objects causes Python script to exit without logging an error 连接数组中的日期时间对象时出错 - Error concatenating datetime objects in an array 如何将包含日期字符串的字典 python 列表强制转换为日期时间对象的 numpy 记录数组? - How do I coerce a python list of dictionaries containing date strings into a numpy record array of datetime objects? pandas 引发日期时间对象的值错误 - pandas raises value error for datetime objects 组合日期和时间 dataframe 对象时出现日期时间错误 - Datetime error in combining date and time dataframe objects Numpy isnat()在datetime对象上返回值错误 - Numpy isnat() returns value error on datetime objects 如何在不更改类型的情况下将充满日期时间对象的元组列表转换为日期时间对象列表? - How to convert a list of tuples full of datetime objects into a list of datetime objects without changing the type?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM