我有一個包含不同記錄時間的資料框作為字串物件,例如1:02:45, 51:11, 54:24。
我無法轉換為時間物件,這是我收到的錯誤:
“時間資料‘49:49’與格式‘%H:%M:%S’不匹配”
這是我正在使用的代碼:
df_plot2 = df[['year', 'gun_time', 'chip_time']]
df_plot2['gun_time'] = pd.to_datetime(df_plot2['gun_time'], format = '%H:%M:%S')
df_plot2['chip_time'] = pd.to_datetime(df_plot2['chip_time'], format = '%H:%M:%S')
在此先感謝您的幫助!
uj5u.com熱心網友回復:
我相信這可能是因為對于 %H,python 期望看到 01、02、03 等而不是 1、2、3。要使用您的具體示例,1:02:45 可能必須采用 01:02:45 格式python 能夠將其轉換為帶有 %H:%M:$S 的日期時間變數。
uj5u.com熱心網友回復:
您可以通過檢查字串 len 并'00:'在只有分鐘和秒的地方將小時添加為零來創建時間序列中的通用格式。然后決議為日期時間。前任:
import pandas as pd
s = pd.Series(["1:02:45", "51:11", "54:24"])
m = s.str.len() <= 5
s.loc[m] = '00:' s.loc[m]
dts = pd.to_datetime(s)
print(dts)
0 2021-12-01 01:02:45
1 2021-12-01 00:51:11
2 2021-12-01 00:54:24
dtype: datetime64[ns]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/370507.html
下一篇:將日期列更改為日期時間
