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

Can not convert pandas columns to datetime

I have below code to create date-time object

import pandas as pd
import datetime as datetime
Dat = pd.DataFrame({'year': [1200, 1400, 1300], 'month': [2,3,4],  'day': [1,2,3]})
datetime.datetime(Dat['year'].astype(int), Dat['month'].astype(int), Dat['day'].astype(int))

With this I am getting below error

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.9/site-packages/pandas/core/series.py", line 141, in wrapper
    raise TypeError(f"cannot convert the series to {converter}")
TypeError: cannot convert the series to <class 'int'>

I am using pandas version as 1.2.3

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

Can you please help me to understand why am I getting this error? What is the correct code?

>Solution :

Use to_datetime with selecting columns:

Dat['date'] = pd.to_datetime(Dat[['year','month','day']])

If only 3 column called year, month, day in Dataframe solution is simplier:

Dat['date'] = pd.to_datetime(Dat)
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