Home > database >  Can not convert pandas columns to datetime
Can not convert pandas columns to datetime

Time:04-05

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

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

CodePudding user response:

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)
  • Related