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

Dataframe – Converting entire column from str object to datetime object – TypeError: strptime() argument 1 must be str, not Series

I want to convert values in entire column from strings to datetime objects, but I can’t accomplish it with this code which works on solo strings i.e. (if I add .iloc[] and specify the index):

price_df_higher_interval['DateTime'] = datetime.datetime.strptime(price_df_higher_interval['DateTime'],
                                                                     '%Y-%m-%d %H:%M:%S')

Also I would like to ommit looping through the dataframe, but I don’t know if that won’t be necessery.

Thank you for your help 🙂

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 :

You could use the pd.to_datetime function.

df = pd.DataFrame({"str_date": ["2023-01-01 12:13:21", "2023-01-02 13:10:24 "]})
df["date"] = pd.to_datetime(df["str_date"], format="%Y-%m-%d %H:%M:%S")
df.dtypes
str_date            object
date        datetime64[ns]
dtype: object

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