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

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

I have a basic dict as follows:

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


        
30条回答
  •  北海茫月
    2020-11-22 04:01

    Here is a simple solution to over come "datetime not JSON serializable" problem.

    enco = lambda obj: (
        obj.isoformat()
        if isinstance(obj, datetime.datetime)
        or isinstance(obj, datetime.date)
        else None
    )
    
    json.dumps({'date': datetime.datetime.now()}, default=enco)
    

    Output:-> {"date": "2015-12-16T04:48:20.024609"}

提交回复
热议问题