2015-10-21 270 views
1

我有兩個DF列與字符串值之間的時間差:大熊貓:計算DF列

df['starttime']       df['endtime'] 

0   2015-10-06 18:35:33   0   2015-10-06 18:35:58 
1  2015-10-08 17:51:21.999000   1   2015-10-08 17:52:10 
2  2015-10-08 20:51:55.999000   2   2015-10-08 20:52:21 
3  2015-10-05 15:16:49.999000   3   2015-10-05 15:17:00 
4  2015-10-05 15:16:53.999000   4   2015-10-05 15:17:22 
5  2015-10-05 15:17:11.999000   5  2015-10-05 15:17:23.999000 

我還想來計算這兩列

這裏的區別是什麼,我嘗試,但未能:

(df['starttime']-df['endtime']).astype('timedelta64[h]')) 

unsupported operand type(s) for -: 'str' and 'str' 

我認爲astype會將str轉換爲timedelta?

+2

你想首先通過'pd.to_datetime()'轉換日期列,然後採取差異? – Zero

+0

工作!謝謝。 –

回答

3

Convert the date strings to pandas.Timestamps:當您嘗試減去兩個系列包含字符串

df['starttime']-df['endtime'] 

unsupported operand type(s) for -: 'str' and 'str' 

發生:

df['starttime']-df['endtime'] 
df['starttime'] = pd.to_datetime(df['starttime']) 
df['endtime'] = pd.to_datetime(df['endtime']) 

然後走差異化而不是首先將字符串轉換爲時間戳。

+0

是的,就是這樣。謝謝! –