How to get the age from a date of birth (DOB) in python ?

How to get the age from a date of birth (DOB) in python ?

Daidalos June 17, 2020


Examples of how to get the age from a date of birth (DOB) in python:

1 -- Calculate the age from a DOB (example 1)

Lets consider the following date of birth: July 8, 1982:

import datetime

dob = datetime.date(1982,8,7)

to get the age of that person at the present day (June 16, 2020), a solution is to defined a function:

def from_dob_to_age(born):
    today = datetime.date.today()
    return today.year - born.year - ((today.month, today.day) < (born.month, born.day))

that returns here

from_dob_to_age(dob)

37 years old !

2 -- Calculate the age from a DOB (example 2)

Another example, lets suppose that the DOB is stored in a string format:

dob = '1982-07-08'

in thta case it is necessary to first convert the string to datetime (see Python string to datetime – strptime() pour plus de details):

dob = datetime.datetime.strptime(dob, '%Y-%m-%d')

and then call the function defined above:

from_dob_to_age(dob)

37 years old !

3 -- Convert a dataframe DOB column to an age column (exemple 3)

Lets consider the following dataframe:

import pandas as pd

data = {'Name':['Ben','Anna','Zoe','Tom','John','Steve'], 
        'dob':['1982-07-08 00:00:00',
               '1987-03-01 00:00:00',
               '2016-02-12 00:00:00',
               '2002-08-14 00:00:00',
               '2011-01-19 00:00:00',
               '2016-03-22 00:00:00']}

df = pd.DataFrame(data)

returns

print(df)

    Name                  dob
0    Ben  1982-07-08 00:00:00
1   Anna  1987-03-01 00:00:00
2    Zoe  2016-02-12 00:00:00
3    Tom  2002-08-14 00:00:00
4   John  2011-01-19 00:00:00
5  Steve  2016-03-22 00:00:00

Convert first the element of the column dob to datetime:

df['Date'] = pd.to_datetime(df.dob)

df['Date']

returns

0   1982-07-08
1   1987-03-01
2   2016-02-12
3   2002-08-14
4   2011-01-19
5   2016-03-22

and the apply the function defined above:

df['Date'].apply(lambda x: from_dob_to_age(x))

0    37
1    33
2     4
3    17
4     9
5     4

4 -- References