Eric
Eric

Reputation: 793

Django: can't subtract offset-naive and offset-aware datetimes

i have a 'free_trial' function in my app that allows users who have an account not older than 7 days to try my app.

user model

from datetime import datetime, timedelta

    class CustomUser(AbstractUser):
    
        def free_trial(self):
            if (self.date_joined - datetime.now()) < timedelta(days=7):
                return True
                    

templates

{% if user.free_trial %}

#Access Features

{% endif %}

but i'm getting this error on template can't subtract offset-naive and offset-aware datetimes

Upvotes: 1

Views: 2716

Answers (2)

ruddra
ruddra

Reputation: 51948

Just use timezone aware time for your calculation:

from django.utils.timezone import localdate

class CustomUser(AbstractUser):

    def free_trial(self):
        if (self.date_joined - localdate()) < timedelta(days=7):
            return True

Upvotes: 3

wiml
wiml

Reputation: 336

One of those datetimes is in a particular time zone ("offset-aware"), and the other is not in any particular timezone ("offset-naïve"), see this part of the Python manual and this previous SO question. They can't be sensibly compared — you either need to add timezone information to one, remove timezone information from the other, or use a seconds-since-the-epoch representation for both. Which one you want to do depends on how you want your application to behave.

Upvotes: 0

Related Questions