Search code examples
pythonpandasdatetimepython-dateutilrelativedelta

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


Here's my data

Customer_id    Date-of-birth
1              1992-07-02
2              1991-07-03

Here's my code

import datetime as dt
df['now'] = dt.datetime.now()
df['age'] = df['now'].dt.date - df['Date-of-birth']

Here's the result

Customer_id    Date-of-birth     age
1              1992-07-02        xxxx days
2              1991-07-03        xxxx days

The result that I want is

Customer_id    Date-of-birth     age
1              1992-07-02        26 years 22 days
2              1991-07-03        27 years 21 days

Just let you now, by df.dtypes, Date-of-birth is an object because is based on customer input in dropdown

How can I achieve this? I hope the question is clear enough


Solution

  • 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