Search code examples
pythonodoo

How to get a person's age from his date of birth in Odoo?


In my module I have an entity "Person" with two fields "date_of_birth" (Date) and "age" (Integer). How can I get the age of a Person from the date of birth and give that value to the age field?


Solution

  • Dates are complicated. If you subtract two dates from each other (assuming datetime.date) you get a timedelta consisting of a number of days. Because of leap years you can't reliably calculate number of years from that. By dividing by 365.25, you get a number of years that's correct in most cases. But most cases is usually not acceptable.

    Instead, you should calculate year difference, offset by -1 if the person has not had their birthday in the current year.

    from datetime import date
    
    def get_age(date_of_birth: date) -> int:
        today = date.today()
        offset = int(date_of_birth.replace(year=today.year) > today)  # int(True) == 1, int(False) == 0
        return date.today().year - date_of_birth.year - offset
    

    Tests

    # On 2020-05-11
    get_age(date(2020, 5, 11))
    >>> 0
    get_age(date(2020, 5, 12))
    >>> -1
    get_age(date(2000, 5, 11))
    >>> 20
    get_age(date(2000, 5, 12))
    >>> 19