简体   繁体   中英

Convert object (time) type column in dataframe to datetime

I am struggling to convert a object type to datetime. It's a column from a dataframe which has time values in format hh:mm:ss.

dataframe: df_train column: time values in format: hh:mm:ss

Below are the options which I already tried without any luck

Opt1:

df_train['time'] = pd.to_datetime(df_train['time'])
Error:
TypeError: <class 'datetime.time'> is not convertible to datetime

Opt2:

df_train['time'] = pd.to_datetime(df_train['time'], format='%H:%M:%S').dt.time
Outcome:
The code is working but the type remain as object.

Opt3:

df_train['time'] = pd.to_datetime(df_train['time'].str.strip(), format='%H:%M:%S')
Outcome:
value changed to NaT

Opt4:

df_train['time'] = pd.to_datetime(df_train['time']).dt.time
Error:
TypeError: <class 'datetime.time'> is not convertible to datetime

Appreciate your suggestions to convert this column to type datetime.

Just try this :

dat['column']  = pd.to_datetime(dat['column'])

OR pd.read_csv(file, parse_dates=['column']) when reading data from file

我想很近,您需要的是to_timedelta for timedeltas,并将python对象时间转换为字符串:

df_train['time'] = pd.to_timedelta(df_train['time'].astype(str))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM