Pandas Get the Age from a Date (Example: Date of Birth)

How do I get an age in years and date on pandas

Use this solution with custom function, because count it is not easy because leaps years:

from dateutil.relativedelta import relativedelta

def f(end):
r = relativedelta(pd.to_datetime('now'), end)
return '{} years {} days'.format(r.years, r.days)

df['age'] = df["Date-of-birth"].apply(f)
print (df)
Customer_id Date-of-birth age
0 1 1992-07-02 26 years 22 days
1 2 1991-07-03 27 years 21 days

Calculating age from date/time format in python/pandas

Is this what you want ?

(pd.to_datetime('today').year-pd.to_datetime('1956-07-01').year)

Out[83]: 61

How to convert a date to different format in Python to calculate age

now = pd.Timestamp('now')
df['dob'] = pd.to_datetime(df['dob'])
df['age'] = (now - df['dob']).astype('<m8[Y]')
print(df)

covert your str into datetime objects

You can subtract dob from now to obtain timedelta64[ns]. To convert that to years, use astype('

for your last formatting

df['dob'].apply(lambda x: x.strftime('%Y/%m/%d'))



Related Topics



Leave a reply



Submit