Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pandas split year from a year-date-time column

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

IIUC use:

df['year'] = pd.to_datetime(df['date_time'], error="coerce").dt.year
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading