postgresql 无法比较偏移天真和偏移感知日期时间 - last_seen 选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31643080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
can't compare offset-naive and offset-aware datetimes - last_seen option
提问by anvd
I want to update the user last seen column. To do that i am trying this user model:
我想更新用户上次看到的列。为此,我正在尝试使用此用户模型:
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()
And this code that run always when the user execute some action.
这段代码总是在用户执行某些操作时运行。
@mod.before_app_request
def before_request():
current_user.ping()
This is the error:
这是错误:
TypeError: can't compare offset-naive and offset-aware datetimes
How can i solve this? I am using postgres and the problem is easily simulated with the code that i am showing.
我该如何解决这个问题?我正在使用 postgres,问题很容易用我展示的代码来模拟。
回答by Simeon Visser
Create an aware datetime (a datetime which has a timezone):
创建一个有意识的日期时间(具有时区的日期时间):
import pytz
self.last_seen = datetime.datetime.utcnow().replace(tzinfo=pytz.UTC)
In this case you'll want to create an aware datetime with the current time in UTC.
在这种情况下,您需要使用 UTC 中的当前时间创建一个有意识的日期时间。
You'll need the pytz
package for this (this package contains the latest timezone information and that information isn't part of the Python standard library).
pytz
为此,您将需要该包(该包包含最新的时区信息,该信息不是 Python 标准库的一部分)。