简体   繁体   English

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

[英]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. 它是数据框中的一列,其时间值格式为hh:mm:ss。

dataframe: df_train column: time values in format: hh:mm:ss 数据帧:df_train列:时间值,格式为:hh:mm:ss

Below are the options which I already tried without any luck 以下是我没有运气就尝试过的选项

Opt1: 选项1:

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

Opt2: 选项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.

Opt3: 选项3:

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

Opt4: 选项4:

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 从文件读取数据时pd.read_csv(file, parse_dates=['column'])pd.read_csv(file, parse_dates=['column'])

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将时间列(对象类型)转换为日期时间格式 - Convert time column (object type) to datetime format 将 DataFrame 列类型从字符串转换为日期时间 - Convert DataFrame column type from string to datetime 如何将 dataframe 中的列转换为索引日期时间 object? - How to convert a column in a dataframe to an index datetime object? 如何将带有日期、时间和 NaN 的对象列转换为 Python Pandas DataFrame 中的 datetime64 列? - How to convert object column with date, time and NaN to datetime64 column in DataFrame in Python Pandas? 将 object 类型转换为时间序列预测中的日期时间 - Convert object type into datetime in Time series Forecasting 如何在熊猫中将对象类型列转换为日期时间 - how to convert an object type column to datetime in panda 将&#39;object&#39;类型的dataframe列转换为类型列表 - convert dataframe column of type 'object' into type list 将类型为“object”的数据框列转换为 set() - Convert dataframe column with type "object" to a set() 如何将数据框的日期和时间列转换为熊猫的datetime格式? - how to convert Date and time column of dataframe to datetime format of pandas? 在 Pandas 数据框中将列类型从字符串转换为日期时间格式 - Convert the column type from string to datetime format in Pandas dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM