Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't compare offset-naive and offset-aware datetimes - last_seen option [duplicate]

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.

like image 502
anvd Avatar asked Jul 26 '15 23:07

anvd


1 Answers

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.

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).

like image 70
Simeon Visser Avatar answered Oct 19 '22 23:10

Simeon Visser