Apr-24-2023, 09:46 AM
You can't do this. A normal year has
Calculate instead the years and not the timedelta.
364
days and a leap year has 365
days.Calculate instead the years and not the timedelta.
import datetime import calendar # today = datetime.date.today() today = datetime.date(2000, 2, 29) bday = datetime.date(1984, 2, 29) years = today.year - bday.year # correct the bday, if it's the 29th february and today is not a leap yaar if bday.month == 2 and bday.day == 29 and not calendar.isleap(today.year): bday = datetime.date(bday.year, 3, 1) # check if today earlier than birthday if (today.month, today.day) < (bday.month, bday.day): years -= 1 # today it's not the birthday, so one year lesser print(years)Improvement of your class:
class Persoon: def __init__(self, naam, sekse, geboortedatum): self._naam = naam self._sekse = sekse self._geboortedatum = datetime.strptime(geboortedatum, "%d-%m-%Y").date() @property def naam(self): return self._naam @property def geb_datum(self): return self._geboortedatum @property def vrouw(self): return self._sekse == "V" @property def man(self): return self._sekse == "M" def leeftijd(self, today=None): today = today or date.today() years = today.year - self.geb_datum.year geboortedatum = self.geb_datum # leap fix 29 feb. if ( geboortedatum.month == 2 and geboortedatum.day == 29 and not isleap(today.year) ): geboortedatum = date(geboortedatum.year, 3, 1) if (today.month, today.day) < (self.geb_datum.month, self.geb_datum.day): years -= 1 return years p1 = Persoon("John", "M", "29-2-1980") # 2023 is not a leap year print(p1.naam, p1.leeftijd(date(2023, 3, 1)))The properties are read-only.
leeftijd()
is still a method, but now you can also set today (better for testing).
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!