1

How du you calculate the time since a model was created? The model has the following field:

created_at = models.DateTimeField(auto_now_add=True)

This is what I tried:

from datetime import datetime, timedelta

@property
def time_since_created(self):
    return (datetime.now()-self.created_at).total_seconds()

What I do not understand is that it crashes without giving me any error messages. If I wrap it in a try/except block like this:

@property
    def time_since_created(self):
        try:
            return (datetime.now()-self.created_at).total_seconds()
        except Exception as e:
            try:
                print("Error:" + e)
            except:
                print("Error: An exception occured when trying to print exception")

The error I will get is "Error: An exception occured when trying to print exception". If I do not include the last try/catch block I won't get any output at all.

Do anyone have any ideas?

2 Answers2

2

I have tried to do the same actions by myself and I have got error:

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

It's because datetime.now() is naive and self.created_at is aware time. So try to use timezone.now() instead:

from django.utils import timezone

@property
def time_since_created(self):
    return (timezone.now()-self.created_at).total_seconds()
bellum
  • 3,642
  • 1
  • 17
  • 22
  • I'm adding dateTime to `time_since_created(dateTime)`. But it gives me this error: **'property' object is not callable** – AnonymousUser Jun 08 '22 at 07:37
-2

Edit: re-post for django solution

After checking previous stackoverflow post here and some other post. They suggest not to using the auto_now_add, but add default argument as format.

created_date = models.DateTimeField(default=datetime.now())

I think it might be the format problem, and this should solve that. And sorry for my previous answer.

Edit: after checking the django source code here, the auto_now_add arg appear to apply

value = datetime.datetime.now().time()

to model instance.

And in my test, if I "minus" this value with datetime.now().time(), it pops

TypeError: unsupported operaand type(s) for -: 'datetime.datetime' and 'datetime.time'

But I'm not sure about your django version, maybe the source code has been modified.

Community
  • 1
  • 1
Jkm
  • 187
  • 1
  • 2
  • 6