I have the following Django model:
created=models.DateTimeField(auto_now_add=True)
I now need a model object method which shows the # of hours since creation. I tried the following:
def hours_live(self):
diff=((datetime.datetime.now - self.created).seconds)/3600
return diff
but it threw a TypeError
unsupported operand type(s) for -: 'builtin_function_or_method' and 'datetime.datetime'
I then went with
def hours_live(self):
diff=((datetime.datetime.now() - self.created).seconds)/3600
return diff
My question is whether the datetime.datetime.now() expression is executed only one time here or whether it executes each time hours_live is called.
Will this work?
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):
You should rather do: