Динамическое изменение даты в python
Пишу калькулятор денег или калорий, который должен подсчитать их сегодня (если введённая дата не совпадает с сегодняшней, подсчет не ведется). Столкнулся с проблемой, что при использовании datetime.today() он перестанет работать, если калькулятор будет работать больше дня. Значение перестанет быть актуальным. Как сделать так, что бы дата автоматически обновлялась всегда?
def __init__(self, limit):
self.limit = limit
self.records = []
'self.today = dt.datetime.today()'
self.remainder = self.limit - self.get_today_stats()
def add_record(self, record):
self.records.append(record)
def get_today_stats(self):
amount_of_money_or_calories = 0
for copy_of_the_record in self.records:
if self.today == copy_of_the_record.date:
amount_of_money_or_calories += copy_of_the_record.amount
return amount_of_money_or_calories
Ответы (2 шт):
Автор решения: eri
→ Ссылка
Можно сделать today вычисляемым свойством
def __init__(self, limit):
self.limit = limit
self.records = []
#'self.today = dt.datetime.today()'
self.remainder = self.limit - self.get_today_stats()
@property
def today(self):
return dt.datetime.today()
def add_record(self, record):
self.records.append(record)
def get_today_stats(self):
amount_of_money_or_calories = 0
for copy_of_the_record in self.records:
if self.today == copy_of_the_record.date:
amount_of_money_or_calories += copy_of_the_record.amount
return amount_of_money_or_calories
Автор решения: Andy Pavlov
→ Ссылка
А почему получение текущей даты не перенести сразу в get_today_stats? Так на каждую проверку будете иметь текущую дату.
class Dummy:
def __init__(self, limit):
self.limit = limit
self.records = []
self.remainder = self.limit - self.get_today_stats()
def add_record(self, record):
self.records.append(record)
def get_today_stats(self):
today = dt.datetime.today()
amount_of_money_or_calories = 0
for copy_of_the_record in self.records:
if today == copy_of_the_record.date:
amount_of_money_or_calories += copy_of_the_record.amount
return amount_of_money_or_calories