将数据框中的对象(时间)类型列转换为日期时间

Convert object (time) type column in dataframe to datetime

我正在努力将对象类型转换为日期时间。 它是数据框中的一列,其时间值格式为 hh:mm:ss.

数据框:df_train 栏目:时间 值格式:hh:mm:ss

以下是我已经尝试过但没有任何运气的选项

选项 1:

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

选项 2:

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.

选项 3:

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

选项 4:

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

感谢您将此列转换为日期时间类型的建议。

试试这个:

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

pd.read_csv(file, parse_dates=['column']) 从文件中读取数据时

我认为接近,你需要的是 to_timedelta 用于将 python 对象时间转换为字符串的时间增量:

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