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

15,603

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

Share:
15,603

Related videos on Youtube

anvd
Author by

anvd

I am a multimedia developer and an open source fan

Updated on September 14, 2022

Comments

  • anvd
    anvd almost 2 years

    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.