0

I have 10 columns (dtype: datetime64). I want to remove the date and month from the columns and keep only the year.

10-01-1880 --> Would like to remove day and month

expecting --> 1880

Jason
  • 103
  • 1
  • 11
  • `df['column'].dt.year` – cs95 Apr 07 '19 at 06:55
  • @coldspeed ... showing error df['year'].dt.year AttributeError: Can only use .dt accessor with datetimelike values – Jason Apr 07 '19 at 07:08
  • From the observation, I can conclude that the type is indeed not `datetime64`. Please verify this information before posting next time... For now, you can do `pd.to_datetime(df['column'], errors='coerce').dt.year`. – cs95 Apr 07 '19 at 07:09
  • @coldspeed... I have already converted my column using pd.to_datetime Name: year, dtype: datetime64[ns].. now I used your code... it showing l0 1970 1 1970 2 1970 3 1970 4 1970 5 1970 6 1970 7 1970 8 1970 9 1970 10 1970 11 1970 12 1970 13 1970 14 1970 15 1970 16 1970 Name: year, dtype: int64 – Jason Apr 07 '19 at 07:12
  • @coldspeed.. I have column which has date-month-year for 25 rows.. I want to remove the date and month and keep the year.. – Jason Apr 07 '19 at 07:13
  • You can't remove the date and month and still retain the type... the year is an integer, so you get a column of integers as a result. – cs95 Apr 07 '19 at 07:25

1 Answers1

0

This should do the trick. I am using datetime module https://docs.python.org/3/library/datetime.html

from datetime import datetime

#Convert string to datetime object
datetime_object = datetime.strptime('10-01-1880', '%d-%m-%Y')
#Extract year
print(datetime_object.day)
print(datetime_object.month)
print(datetime_object.year)
#10
#1
#1880
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40