0

I have a dataframe 'df' with one column called 'date_time' that has values in this format "2018-01-01T00:00:00-05:00". I want to split it so I have just the year "2018" in a new column.

I tried df['year'] = df["date_time"].str.split("-", n=1, expand = False) I get a new column called 'year' with a list [2018, 01-01T00:00:00-05:00] But I want to split it so I have just the year 2018 in the new column.

preetix
  • 1
  • 1

1 Answers1

0

IIUC use:

df['year'] = pd.to_datetime(df['date_time'], error="coerce").dt.year
Kayvan Shah
  • 375
  • 2
  • 11
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252