0

I got a dateframe which there is one column 'brth_dt' and its type is datetime64[ns].I want to extract the age of persons,however when input: all_df['brth_dt'].dt.year or
all_df['age'] = (pd.datetime.today().year - all_df['brth_dt'].dt.year)

coming up an error:can only use .dt accessor with datetimelike values

brth_dt columns are like this:

    brth_date
1   14Oct1978
2   21Aug1970
3   06Jan1980
4   09Mar1992

any advice?thanks!

cs95
  • 379,657
  • 97
  • 704
  • 746
Lucy
  • 45
  • 1
  • 1
  • 7

1 Answers1

8

You need to convert the column to datetime first using

df['brth_date'] = pd.to_datetime(df['brth_date'], format = '%d%b%Y')

The you can use the dt accessor

df['brth_date'].dt.year

You get

1    1978
2    1970
3    1980
4    1992
Vaishali
  • 37,545
  • 5
  • 58
  • 86
  • thanks..hiwever,df.info() shows this column is datetime64[ns] and df['brth_date'] = pd.to_datetime(df['brth_date'], format = '%d%b%Y') comes up with KeyError – Lucy Sep 18 '17 at 04:09
  • That's surprising as the datetime values are usually in 1978-10-14 format. What is the exact keyerror message? – Vaishali Sep 18 '17 at 04:16
  • yes its type is datetime64[ns] and in 14Oct1978 format,that's what I am curious about... – Lucy Sep 18 '17 at 04:41