How to overcome “datetime.datetime not JSON serializable”?

后端 未结 30 3248
梦谈多话
梦谈多话 2020-11-22 03:31

I have a basic dict as follows:

sample = {}
sample[\'title\'] = \"String\"
sample[\'somedate\'] = somedatetimehere
         


        
30条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 04:03

    Generally there are several ways to serialize datetimes, like:

    1. ISO string, short and can include timezone info, e.g. @jgbarah's answer
    2. Timestamp (timezone data is lost), e.g. @JayTaylor's answer
    3. Dictionary of properties (including timezone).

    If you're okay with the last way, the json_tricks package handles dates, times and datetimes including timezones.

    from datetime import datetime
    from json_tricks import dumps
    foo = {'title': 'String', 'datetime': datetime(2012, 8, 8, 21, 46, 24, 862000)}
    dumps(foo)
    

    which gives:

    {"title": "String", "datetime": {"__datetime__": null, "year": 2012, "month": 8, "day": 8, "hour": 21, "minute": 46, "second": 24, "microsecond": 862000}}
    

    So all you need to do is

    `pip install json_tricks`
    

    and then import from json_tricks instead of json.

    The advantage of not storing it as a single string, int or float comes when decoding: if you encounter just a string or especially int or float, you need to know something about the data to know if it's a datetime. As a dict, you can store metadata so it can be decoded automatically, which is what json_tricks does for you. It's also easily editable for humans.

    Disclaimer: it's made by me. Because I had the same problem.

提交回复
热议问题