How can I calculate the age of a person in year, month, days?

前端 未结 11 1214
谎友^
谎友^ 2020-11-27 05:52

I want to calculate the age of a person given the date of birth and the current date in years, months and days relative to the current date.

For example:

<         


        
11条回答
  •  暖寄归人
    2020-11-27 06:22

    I know it's a bit outdated, but here is a simple code that I used,with the power of the Python library (Python 3.5 for annotations, but works without).

    from datetime import date, timedelta
    
    def age(birth: date) -> (int, int, int):
            """
                Get a 3-int tuple telling the exact age based on birth date.
            """
            today_age = date(1, 1, 1) + (date.today() - birth)
            # -1 because we start from year 1 and not 0.
            return (today_age.year - 1, today_age.month - 1, today_age.day - 1)
    

提交回复
热议问题