简体   繁体   中英

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

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

Input:

import pandas as pd
import datetime as dt

now = dt.datetime.now()
for i in range(0, len(df)):
    diff = now - dt.datetime.strptime(df['Date-of-Birth'][i], '%Y-%m-%d')
    years = diff.days // 365
    days = diff.days - (years*365)
    df['age'][i] = str(years) + ' years ' + str(days) + ' days'

print(df)

Output:

Customer_id     Date-of-Birth          age
    1            1992-07-04       26 years 25 days
    2            1991-07-04       27 years 26 days

Maybe you could use something like the following. Note that it relies on the fact that the average year has 365.25 days, so it may be a day off sometimes.

import datetime as dt

def year_days_diff(x):
    diff = (dt.datetime.now() - x).days
    return str(int(diff / 365.25)) + ' years ' + str(int(diff / 365.25 % 1 * 365.25)) + ' days'

Example:

birth_date = dt.datetime.now() - dt.timedelta(10000)
year_days_diff(birth_date)

output:

'27 years 138 days'

This could give you age by rounding to years.

ref_date = dt.datetime.now()
df['age'] = df['Date-of-birth'].apply(lambda x: len(pd.date_range(start = x, end = ref_date, freq = 'Y'))) 

Use astype('<m8[Y]')

Ex:

df['age'] = (pd.to_datetime('now') - df['Date-of-birth']).astype('<m8[Y]')

Demo:

import pandas as pd

df = pd.DataFrame({"Date-of-birth": pd.to_datetime(['1992-07-24', '1991-07-24'])})
df["age"] = (pd.to_datetime('now') - df["Date-of-birth"]).astype('<m8[Y]')
print(df)

Output:

  Date-of-birth   age
0    1992-07-24  25.0
1    1991-07-24  27.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM