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

后端 未结 30 3251
梦谈多话
梦谈多话 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

    Actually it is quite simple. If you need to often serialize dates, then work with them as strings. You can easily convert them back as datetime objects if needed.

    If you need to work mostly as datetime objects, then convert them as strings before serializing.

    import json, datetime
    
    date = str(datetime.datetime.now())
    print(json.dumps(date))
    "2018-12-01 15:44:34.409085"
    print(type(date))
    
    
    datetime_obj = datetime.datetime.strptime(date, '%Y-%m-%d %H:%M:%S.%f')
    print(datetime_obj)
    2018-12-01 15:44:34.409085
    print(type(datetime_obj))
    
    

    As you can see, the output is the same in both cases. Only the type is different.

提交回复
热议问题