I am trying to describe the behavior of some objects and I need to store how long each of them is active. So I resort to timedelta
:
import datetime
class Activos:
def __init__(self, tinicio=datetime.datetime.now(), duracion=datetime.timedelta(seconds=0)):
self.tinicio = tinicio
self.duracion = duracion
def cronos(self):
aloha = datetime.datetime.now()-self.tinicio
jour = aloha.days
gundo = aloha.seconds
self.duracion = datetime.timedelta(days=jour, seconds=gundo)
Since when I do:
....
def cronos(self):
self.duracion = datetime.timedelta(datetime.datetime.now()-self.tinicio)
The following appears:
# TypeError: unsupported type for timedelta days component: datetime.datetime
My question is if it could be updated Activos.duracion
automatically, without having to call a function (or method) to do it . Maybe touching initialization variables?:
import datetime
class Momento:
def __init__(self, tinicio=datetime.datetime.now(), duracion=datetime.timedelta(0)):
self.tinicio = tinicio
self.duracion = datetime.timedelta(datetime.datetime.now()-self.tinicio)
But then the same error would appear again.
Thank you for your time (never better said :) )
By subtracting two
datetimes
you directly get atimedelta
. You do not need to instantiate one (let alone pass the subtraction as a parameter, because then you are passing it anothertimedelta
).An example:
Result:
Answering the question in a comment
There are no class attributes that update "automatically", there must always be some code to do so. In any case, even if you had a field
duracion
that only magically updated, at some point you will query it, I say. So why not compute that attribute at the time of the query?For example a mere name change gives you another perspective:
But we can still do something else, which is already very close to the "automatic update" you were looking for.
In this case the object doesn't really have an attribute
duracion
, but by declaring the functionduracion()
as@property
, it will be executed when you try to access the attributeej.duracion
, producing the "illusion" that it is a real attribute and that it has the elapsed time (when in fact the result is computed at the time of evaluation)