Convert DOB to age

I have the following and am returning an error

import pandas as pd
import numpy as np
from datetime import datetime

My df is

Code DOB
1586 01/06/1980
3589 15/05/1976
1276 10/06/2010

I want to return

Code DOB Age
1586 01/06/1980 43
3589 15/05/1976 48
1276 10/06/2010 13

I am using the below

def age(born):
born = datetime.strptime(born, "%d/%m/%Y" ).date()
today = date.today()
return today.year - born.year - ((today.month,today.day) < (born.month,born.day))
df[ 'Age' ] = df[ 'DOB' ]. apply (age)

I am getting an error: strptime() argument 1 must be str, not Timestamp

How do I fix this to return an age based from a date of birth?

I have also tried the following:

(now) = pd.to_datetime(‘now’)
df[‘age’] = (now.year - df]‘DOB’].datetime.year) - ((now.month - df[‘DOB’].datetime.month) < 0)

and get the following error
‘series’ object has no attribute to ‘datetime’

Your DOB column doesn’t actually contain strings with slashes in them (what strptime would convert). It contains instances of Pandas’ Timestamp class. To work with these, see the documentation etc. according to your intended approach to the problem:

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Timestamp.html

https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Timestamp.now.html

For future posts, please read the pinned thread in order to understand how to format code properly.

1 Like