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

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

Asked on October 13, 2018 in Python.
Add Comment


  • 8 Answer(s)

            Construction on other answers, just a simple solution based on a precise serializer that just converts datetime.datetime and datetime.date objects to strings.

     
    from datetime import date, datetime
        def json_serial(obj):
            """JSON serializer for objects not serializable by default json code"""
        if isinstance(obj, (datetime, date)):
            return obj.isoformat()
            raise TypeError ("Type %s not serializable" % type(obj))
     
    

            As seen, the code simply checks to seek out out if object is of sophistication datetime.datetime or datetime.date, then uses .isoformat() to provide a serialized version of it, in step with ISO 8601 format, YYYY-MM-DDTHH:MM:SS (which is well decoded by JavaScript). If additional advanced serialized representations area unit sought-after, different code may be used rather than str() (see different answers to the present question for examples). The code ends by raising AN exception, to manage the case it’s known as with a non-serializable kind.

     

        This json_serial perform is used as follows:

     
        from datetime import datetime
        from json import dumps
        print dumps(datetime.now(), default=json_serial)
     
    

     

    Answered on October 13, 2018.
    Add Comment

    My quick & dirty JSON dump that eats dates and everything:

    json.dumps(my_dictionary, indent=4, sort_keys=True, default=str)
    
    Answered on October 15, 2018.
    Add Comment

    I have just come across this problem and my solution is to subclass json.JSON Encoder:

     
    from datetime import datetime
    import json
    class DateTime Encoder(json.JSONEncoder):
    def default(self, o):
    if isinstance(o, datetime):
    return o.isoformat()
    return json.JSONEncoder.default(self, o)
     
    

     

    In your call do something like: json.dumps(your obj, cls=DateTimeEncoder) The .isoformat() I got from one of the answers above.

    Answered on October 15, 2018.
    Add Comment
    import datetime
    import json
    def default(o):
    if isinstance(o, (datetime.date, datetime.datetime)):
    return o.isoformat()
    return json.dumps(
    item,
    sort_keys=True,
    indent=1,
    default=default
    
    Answered on December 16, 2018.
    Add Comment

    the given code is

    from datetime import datetime
    def json_serial(obj):
    
    """JSON serializer for objects not serializable by default json code"""
    if isinstance(obj, datetime):
    
    serial = obj.isoformat()
    
    return serial
    
    raise TypeError ("Type not serializable")
    
    Answered on December 16, 2018.
    Add Comment
    def default(obj):
        """Default JSON serializer."""
        import calendar, datetime
    
        if isinstance(obj, datetime.datetime):
            if obj.utcoffset() is not None:
                obj = obj - obj.utcoffset()
            millis = int(
                calendar.timegm(obj.timetuple()) * 1000 +
                obj.microsecond / 1000
            )
            return millis
        raise TypeError('Not sure how to serialize %s' % (obj,))
    
    

    Then use it like so:

    import datetime, json
    print json.dumps(datetime.datetime.now(), default=default)

    output:

    '1365091796124'
    Answered on January 14, 2019.
    Add Comment

    The original answer accommodated the way MongoDB “date” fields were represented as:

    {“$date”: 1506816000000}

    If you want a generic Python solution for serializing datetime to json, check out @jjmontes’ answer for a quick solution which requires no dependencies.

    As you are using mongoengine (per comments) and pymongo is a dependency, pymongo has built-in utilities to help with json serialization:
    http://api.mongodb.org/python/1.10.1/api/bson/json_util.html

    Example usage (serialization):

    from bson import json_util
    import json

    json.dumps(anObject, default=json_util.default)
    Example usage (deserialization):

    json.loads(aJsonString, object_hook=json_util.object_hook)

    Answered on February 4, 2019.
    Add Comment

    The original answer accommodated the way MongoDB “date” fields were represented as:

    {"$date": 1506816000000}

    If you want a generic Python solution for serializing datetime to json, check out @jjmontes’ answer for a quick solution which requires no dependencies.


    As you are using mongoengine (per comments) and pymongo is a dependency, pymongo has built-in utilities to help with json serialization:
    http://api.mongodb.org/python/1.10.1/api/bson/json_util.html

    Example usage (serialization):

    from bson import json_util
    import json
    
    json.dumps(anObject, default=json_util.default)

    Example usage (deserialization):

    json.loads(aJsonString, object_hook=json_util.object_hook)

    Django

    Django provides a native DjangoJSONEncoder serializer that deals with this kind of properly.

    See https://docs.djangoproject.com/en/dev/topics/serialization/#djangojsonencoder

    from django.core.serializers.json import DjangoJSONEncoder
    
    return json.dumps(
      item,
      sort_keys=True,
      indent=1,
      cls=DjangoJSONEncoder
    )

    One difference I’ve noticed between DjangoJSONEncoder and using a custom default like this:

    import datetime
    import json
    
    def default(o):
        if isinstance(o, (datetime.date, datetime.datetime)):
            return o.isoformat()
    
    return json.dumps(
      item,
      sort_keys=True,
      indent=1,
      default=default
    )

    Is that Django strips a bit of the data:

     "last_login": "2018-08-03T10:51:42.990", # DjangoJSONEncoder 
     "last_login": "2018-08-03T10:51:42.990239", # default
    Answered on February 9, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.