簡體   English   中英

將數據框中的對象(時間)類型列轉換為日期時間

[英]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'])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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM