无法比较偏移天真和偏移感知日期时间 - last_seen 选项 [重复]

Posted

技术标签:

【中文标题】无法比较偏移天真和偏移感知日期时间 - last_seen 选项 [重复]【英文标题】:can't compare offset-naive and offset-aware datetimes - last_seen option [duplicate] 【发布时间】:2015-10-17 01:08:36 【问题描述】:

我想更新用户上次看到的列。为此,我正在尝试这个用户模型:

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    ...
    last_seen = db.Column(db.DateTime(timezone=True), default=datetime.datetime.utcnow)

    def ping(self):
        self.last_seen = datetime.datetime.utcnow()
        db.session.add(self)
        db.session.commit()

当用户执行某些操作时,此代码始终运行。

@mod.before_app_request
def before_request():
    current_user.ping()

这是错误:

TypeError: can't compare offset-naive and offset-aware datetimes

我该如何解决这个问题?我正在使用 postgres,问题很容易用我展示的代码来模拟。

【问题讨论】:

【参考方案1】:

创建可感知的日期时间(具有时区的日期时间):

import pytz

self.last_seen = datetime.datetime.utcnow().replace(tzinfo=pytz.UTC)

在这种情况下,您需要使用 UTC 的当前时间创建一个感知日期时间。

为此,您需要 pytz 包(此包包含最新的时区信息,该信息不属于 Python 标准库的一部分)。

【讨论】:

以上是关于无法比较偏移天真和偏移感知日期时间 - last_seen 选项 [重复]的主要内容,如果未能解决你的问题,请参考以下文章