【问题标题】:Sqlalchemy postgreSQL read timestamp with time zone as Europe/BerlinSqlalchemy postgreSQL 读取时间戳,时区为欧洲/柏林
【发布时间】:2019-06-22 14:03:47
【问题描述】:

我的数据库中有带时区的时间戳。这些始终以 UTC 创建。

我需要向欧洲/柏林的用户显示时间。现在我需要用 JS 或 Jinja2 修改任何地方的时间以显示正确的时间。我觉得应该有一个全球性的解决方案,但我找不到。

这是一个例子(模型):

class User(UserMixin, Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    date_added = Column(DateTime(timezone=True), nullable=False)

下面是创建用户时的代码:

new_user = User(date_added=datetime.today())

这个操作系统在数据库中的样子:

我曾经使用过一个 MySQL 数据库并且我正在使用它:

db_session.execute("SET SESSION time_zone = 'Europe/Berlin'")

posgreSQL 有类似的东西吗?

【问题讨论】:

  • 您的意思是SET 命令允许您为每个会话或每个事务指定配置参数?是的,PostgreSQL has something like that :)
  • postgres default timezone的可能重复
  • 如果你从一个已经设置了值的表中读取,并且在一个带有时区的时间戳中,可以尝试select <your timestamp> at time zone 'Europe/Berlin'。我认为设置 session 参数很有用,但仅适用于新记录。
  • 遗憾的是,我无法进一步发表评论,但重复帖子中的解决方案都不起作用,pgadmin 版本太旧了。并且通过查询工具设置时区只会改变当前表,在重新启动它回到 UTC 之后也是如此。
  • NVM。找到它,接受的答案是错误的:ALTER DATABASE postgres SET timezone TO 'Europe/Berlin';

标签: python postgresql flask sqlalchemy timestamp-with-timezone


【解决方案1】:

我认为您的数据库应该与时区无关。我通常在显示我的 PostgreSQL 数据库中的日期时间之前调用此函数:

from pytz import timezone, UTC

def to_user_timezone(dt):
    """Convert a datetime object to the user's timezone.  If you need
    to convert a :class:`datetime.datetime` object at any time to the user's
    timezone (as returned by :func:`get_timezone` this function can be used).
    """
    if dt.tzinfo is None:
        dt = dt.replace(tzinfo=UTC)
    tzinfo = timezone('Europe/Berlin')
    return tzinfo.normalize(dt.astimezone(tzinfo))

【讨论】:

    猜你喜欢
    • 2021-09-16
    • 1970-01-01
    • 2021-05-03
    • 2014-05-19
    • 2020-05-24
    • 2021-04-21
    • 2018-10-30
    • 2023-03-12
    • 2013-09-12
    相关资源
    最近更新 更多