Python - When is a timedelta object processed?

I have the following Django model:

   created=models.DateTimeField(auto_now_add=True)

I now need a model object method that shows the number of hours since it was created. I tried the following:

  def hours_live(self):
    diff=((datetime.datetime.now - self.created).seconds)/3600
    return diff   

but he chose TypeError

unsupported operand type(s) for -: 'builtin_function_or_method' and 'datetime.datetime'

Then i went with

 def hours_live(self):
    diff=((datetime.datetime.now() - self.created).seconds)/3600
    return diff   

My question is whether the expression datetime.datetime.now () is executed only once here or is it executed every time hour_live is called.

Will this work?

+3
source share
3 answers

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

: ( , ):

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

:

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

datetime.datetime.now - . , , . , , , .

+6

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

+3
source

All Articles