Skip to main content
 首页 » 编程设计

python之Django:类型为 'datetime' 的对象不是 JSON 可序列化的

2024年09月03日34zfyouxi

我正在尝试在我的 session 中保存一个日期。我总是收到错误 Object of type 'datetime' is not JSON serializable。我找到了这个 here在 Django 文档中:存储为自纪元以来的秒数,因为日期时间在 JSON 中不可序列化。

如何将我的 expiry_date 保存为秒而不是日期时间?

code = social_ticketing_form.cleaned_data['a'] 
expiry_date = timezone.now() + timezone.timedelta(days=settings.SOCIAL_TICKETING_ATTRIBUTION_WINDOW) 
request.session[social_ticketing_cookie_name(request.event)] = {'code': code, 'expiry_date': expiry_date} 

请您参考如下方法:

或者write your own session serialiser允许您直接序列化 datetime 对象,或以其他形式存储 datetime 值。

如果你想把它保存为秒,然后使用 datetime.timestamp() method :

request.session[social_ticketing_cookie_name(request.event)] = { 
    'code': code,  
    'expiry_date': expiry_date.timestamp() 
} 

自己的SESSION_SERIALIZER类只需要提供loads和dumps方法即可,直接类比json.loads() 和 json.dumps()(这就是 standard JSON serializer is implemented 的方式)。

如果你想对 datetime 对象进行编码并能够透明地将它们再次转换回 datetime 对象,我会使用嵌套对象格式来标记这样的值特别:

from datetime import datetime 
 
class JSONDateTimeSerializer: 
    @staticmethod 
    def _default(ob): 
        if isinstance(ob, datetime): 
            return {'__datetime__': ob.isoformat()} 
        raise TypeError(type(ob)) 
 
    @staticmethod 
    def _object_hook(d): 
        if '__datetime__' in d: 
            return datetime.fromisoformat(d['__datetime__']) 
        return d 
 
    def dumps(self, obj): 
        return json.dumps( 
            obj, separators=(',', ':'), default=self._default 
        ).encode('latin-1') 
 
    def loads(self, data): 
        return json.loads( 
            data.decode('latin-1'), object_hook=self._object_hook 
        ) 

并将 SESSION_SERIALIZER 设置为上述模块的完整限定名称 (path.to.module.JSONDateTimeSerializer)。

上面使用了datetime.fromisoformat() method , Python 3.7 中的新功能。