【问题标题】:can't compare offset-naive and offset-aware datetimes - last_seen option [duplicate]无法比较偏移天真和偏移感知日期时间 - last_seen 选项 [重复]
【发布时间】: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,问题很容易用我展示的代码来模拟。

【问题讨论】:

    标签: python sql postgresql datetime flask


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2015-06-15
      • 2020-12-30
      • 2010-10-22
      • 2021-07-07
      • 1970-01-01
      • 2020-11-07
      • 1970-01-01
      • 2012-10-09
      相关资源
      最近更新 更多