13

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.

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
anvd
  • 3,997
  • 19
  • 65
  • 126

1 Answers1

15

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

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180