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

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

I have a basic dict as follows:

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


        
30条回答
  •  Happy的楠姐
    2020-11-22 03:58

    I got the same error message while writing the serialize decorator inside a Class with sqlalchemy. So instead of :

    Class Puppy(Base):
        ...
        @property
        def serialize(self):
            return { 'id':self.id,
                     'date_birth':self.date_birth,
                      ...
                    }
    

    I simply borrowed jgbarah's idea of using isoformat() and appended the original value with isoformat(), so that it now looks like:

                      ...
                     'date_birth':self.date_birth.isoformat(),
                      ...
    

提交回复
热议问题