-2

I have a dataframe df with a DOB (date of birth) that is in the format of "Year-Month-Day (1994-01-01)" and the DOB variable is an object. I need to assign age to each person using this DOB variable. I noticed I need to use datetime to find age, and I need to convert the format to "Year/Month/Day (1994/01/01)" first.

I wonder if someone can help.

Thanks!

Benn
  • 59
  • 7
  • Please post an example input and your expected output. `"Year-Month-Day" ` can mean various things (`99-03-02` or `1999-3-2`?) – Selcuk Jun 08 '20 at 02:50
  • Thanks for the notice. I just edited as you mentioned. – Benn Jun 08 '20 at 02:53
  • 1
    Does this answer your question? [Pandas get the age from a date (example: date of birth)](https://stackoverflow.com/questions/26788854/pandas-get-the-age-from-a-date-example-date-of-birth) -> see esp. [cs95's answer](https://stackoverflow.com/a/55670911/10197418). – FObersteiner Jun 08 '20 at 06:13

1 Answers1

0
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'))

Kuldeep Singh Sidhu
  • 3,748
  • 2
  • 12
  • 22
  • for converting the format I ran your code and got this error: ```AttributeError: 'str' object has no attribute 'strftime'``` – Benn Jun 08 '20 at 04:03
  • `strftime` is string from time which is a datetime attribute so first convert it into datetime using the above code then use it. – Kuldeep Singh Sidhu Jun 08 '20 at 04:23
  • Thanks! It worked and I wonder what ```m8[Y]``` does? and if this way gives me the exact age or just subtracting ```current year``` from the ```birth year``` and ignoring ```day and month```? – Benn Jun 08 '20 at 04:50
  • to convert to years use astype(' – Kuldeep Singh Sidhu Jun 08 '20 at 04:52
  • I mean if this part : ```now - df['dob']``` calculates the exact age? – Benn Jun 08 '20 at 04:57