SQLAlChemy如何使用TIMEZONE=UTC(不带时区存储的日期)加载日期 [英] SQLAlchemy How to load dates with timezone=UTC (dates stored without timezone)

查看:0
本文介绍了SQLAlChemy如何使用TIMEZONE=UTC(不带时区存储的日期)加载日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,其日期列定义为:

created_on = db.Column(db.DateTime, default=db.func.now(), nullable=False)
日期以tz_INFO=NONE表示,这是正确的,因为日期是存储的 没有时区信息。

如果我打印日期:

print(my_object.created_on.isoformat())

我得到此格式

2014-04-26T17:46:27.353936

我希望有一个UTC时区指示器,例如:

2014-04-26T17:46:27.353936Z

有没有办法在架构配置中定义此行为?

SQLAlChemy Has,TimeZone=Boolean

sqlalchemy.types.DateTime(timezone=False)

因为我希望存储不带时区。

推荐答案

您需要一个自定义数据类型,如下所示:http://docs.sqlalchemy.org/en/rel_0_9/core/types.html#custom-types

具体地说,应该是这样的:

import pytz  # from PyPI

class AwareDateTime(db.TypeDecorator):
    '''Results returned as aware datetimes, not naive ones.
    '''

    impl = db.DateTime

    def process_result_value(self, value, dialect):
        return value.replace(tzinfo=pytz.utc)

然后将该栏设置为:

created_on = db.Column(AwareDateTime, default=db.func.now(), nullable=False)

这篇关于SQLAlChemy如何使用TIMEZONE=UTC(不带时区存储的日期)加载日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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