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

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

I have a basic dict as follows:

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


        
30条回答
  •  旧巷少年郎
    2020-11-22 04:10

    For others who do not need or want to use the pymongo library for this.. you can achieve datetime JSON conversion easily with this small snippet:

    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'
    

提交回复
热议问题