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 datetimedob = 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 pddata = {'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 dob0 Ben 1982-07-08 00:00:001 Anna 1987-03-01 00:00:002 Zoe 2016-02-12 00:00:003 Tom 2002-08-14 00:00:004 John 2011-01-19 00:00:005 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-081 1987-03-012 2016-02-123 2002-08-144 2011-01-195 2016-03-22
and the apply the function defined above:
df['Date'].apply(lambda x: from_dob_to_age(x))0 371 332 43 174 95 4
