[Django]-Python–When is timedelta object processed?

5👍

In your example, it will be executed every time the function is called. The gotcha is when datetime.datetime.now() is used as a default value for a parameter in a function definition. In that case, it is executed just once when the module is loaded.

For example: (this is dangerous because since is calculated only once when the module is loaded):

def hours_live(since=datetime.datetime.now()):
    return since - self.created

You should rather do:

def hours_live(since=None):
    if not since:
        since = datetime.datetime.now()
    return since - self.created

6👍

datetime.datetime.now is a method. When you call it without parentheses, you are referring to the method itself, and you can’t subtract a time from a method. When you call it with parentheses, you are calling the method, getting the return value, and then using that for subtraction.

👤mipadi

3👍

Of course it’s executed every time hours_live is called, it’s a normal function call.

Leave a comment