SQLAlchemy DateTime对象只能天真吗? [英] Can SQLAlchemy DateTime Objects Only Be Naive?

查看:103
本文介绍了SQLAlchemy DateTime对象只能天真吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用SQLAlchemy,而且我还不知道我将使用哪个数据库,所以我希望尽可能地保持与DB无关。如何在数据库中存储有时区感知的datetime对象,而不必将自己绑定到特定的数据库?现在,我确保时间是UTC,然后将其存储在数据库中,并在显示时转换为本地化,但感觉不够脆弱。有没有DB-agnostic方法来获取SQLAlchemy中的时区识别datetime,而不是从数据库中获取天真的数据时间对象?

I am working with SQLAlchemy, and I'm not yet sure which database I'll use under it, so I want to remain as DB-agnostic as possible. How can I store a timezone-aware datetime object in the DB without tying myself to a specific database? Right now, I'm making sure that times are UTC before I store them in the DB, and converting to localized at display-time, but that feels inelegant and brittle. Is there a DB-agnostic way to get a timezone-aware datetime out of SQLAlchemy instead of getting naive datatime objects out of the DB?

推荐答案

时区参数。日期时间rel =noreferrer> DateTime 列时间,所以没有问题存储时区感知 datetime 对象。但是,我发现使用简单的类型装饰器可以方便地将存储的 datetime 转换为UTC:

There is a timezone parameter to DateTime column time, so there is no problem with storing timezone-aware datetime objects. However I found convenient to convert stored datetime to UTC automatically with simple type decorator:

from sqlalchemy import types
from dateutil.tz import tzutc
from datetime import datetime

class UTCDateTime(types.TypeDecorator):

    impl = types.DateTime

    def process_bind_param(self, value, engine):
        if value is not None:
            return value.astimezone(tzutc())

    def process_result_value(self, value, engine):
        if value is not None:
            return datetime(value.year, value.month, value.day,
                            value.hour, value.minute, value.second,
                            value.microsecond, tzinfo=tzutc())

请注意,当您意外使用天真的 datetime 时,表现很好(意味着它会引发ValueError)。

Note, that is behaves nicely when you use naive datetime by accident (meaning it will raise a ValueError).

这篇关于SQLAlchemy DateTime对象只能天真吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆