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

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

I have a basic dict as follows:

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


        
30条回答
  •  名媛妹妹
    2020-11-22 03:52

    If you are on both sides of the communication you can use repr() and eval() functions along with json.

    import datetime, json
    
    dt = datetime.datetime.now()
    print("This is now: {}".format(dt))
    
    dt1 = json.dumps(repr(dt))
    print("This is serialised: {}".format(dt1))
    
    dt2 = json.loads(dt1)
    print("This is loaded back from json: {}".format(dt2))
    
    dt3 = eval(dt2)
    print("This is the same object as we started: {}".format(dt3))
    
    print("Check if they are equal: {}".format(dt == dt3))
    

    You shouldn't import datetime as

    from datetime import datetime
    

    since eval will complain. Or you can pass datetime as a parameter to eval. In any case this should work.

提交回复
热议问题