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

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

I have a basic dict as follows:

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


        
30条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 04:07

    This Q repeats time and time again - a simple way to patch the json module such that serialization would support datetime.

    import json
    import datetime
    
    json.JSONEncoder.default = lambda self,obj: (obj.isoformat() if isinstance(obj, datetime.datetime) else None)
    

    Than use json serialization as you always do - this time with datetime being serialized as isoformat.

    json.dumps({'created':datetime.datetime.now()})
    

    Resulting in: '{"created": "2015-08-26T14:21:31.853855"}'

    See more details and some words of caution at: StackOverflow: JSON datetime between Python and JavaScript

提交回复
热议问题