python pandas: 减去两个日期时间得到零
python pandas: substracting two datetimes gives zero
df['time2'] = pd.to_datetime( df['time'], format = "%H:%M:%S", errors="coerce") #create datetime
df['timestart'] = df.iloc[[0]]['time2'] #create start time
df['timediff'] = ( df['time2'] - df['timestart']) #substract start_time from current time
但我得到的只是
名称:time2,数据类型:datetime64[ns]
时间
time2
时间开始
时差
09:00:00
1900-01-0109:00:00
1900-01-0109:00:00
0 天
10:10:00
1900-01-0110:10:00
1900-01-0109:00:00
0 天
11:08:00
1900-01-0111:08:00
1900-01-0109:00:00
0 天
12:12:00
1900-01-0112:12:00
1900-01-0109:00:00
0 天
“0 天”不是我所期望的。我需要
00:00:00
01:10:00
02:08:00
etc.
df = pd.DataFrame(np.array(["09:00:00","10:10:00","11:08:00","12:12:00","13:09:00","14:09:00","15:09:00","16:01:00","16:46:00"]),columns=['time'])
df['time2'] = pd.to_datetime( df['time'], format = "%H:%M:%S", errors="coerce")
starttime = df['time2'].iloc[0]
df['timediff'] = (df['time2'] - starttime )
如果你想要总秒数,那么你可以使用:
df['timediff']=df['timediff'].dt.total_seconds()
如果你只需要时间部分(你不关心天数):
df['timediff']=pd.to_datetime(df['timediff'].dt.total_seconds(),unit='s').dt.time
df
的输出:
time time2 timestart timediff
0 09:00:00 1900-01-01 09:00:00 1900-01-01 09:00:00 0 days 00:00:00
1 10:10:00 1900-01-01 10:10:00 1900-01-01 09:00:00 0 days 01:10:00
2 11:08:00 1900-01-01 11:08:00 1900-01-01 09:00:00 0 days 02:08:00
3 12:12:00 1900-01-01 12:12:00 1900-01-01 09:00:00 0 days 03:12:00
df['time2'] = pd.to_datetime( df['time'], format = "%H:%M:%S", errors="coerce") #create datetime
df['timestart'] = df.iloc[[0]]['time2'] #create start time
df['timediff'] = ( df['time2'] - df['timestart']) #substract start_time from current time
但我得到的只是
名称:time2,数据类型:datetime64[ns]
时间 | time2 | 时间开始 | 时差 |
---|---|---|---|
09:00:00 | 1900-01-0109:00:00 | 1900-01-0109:00:00 | 0 天 |
10:10:00 | 1900-01-0110:10:00 | 1900-01-0109:00:00 | 0 天 |
11:08:00 | 1900-01-0111:08:00 | 1900-01-0109:00:00 | 0 天 |
12:12:00 | 1900-01-0112:12:00 | 1900-01-0109:00:00 | 0 天 |
“0 天”不是我所期望的。我需要
00:00:00
01:10:00
02:08:00
etc.
df = pd.DataFrame(np.array(["09:00:00","10:10:00","11:08:00","12:12:00","13:09:00","14:09:00","15:09:00","16:01:00","16:46:00"]),columns=['time'])
df['time2'] = pd.to_datetime( df['time'], format = "%H:%M:%S", errors="coerce")
starttime = df['time2'].iloc[0]
df['timediff'] = (df['time2'] - starttime )
如果你想要总秒数,那么你可以使用:
df['timediff']=df['timediff'].dt.total_seconds()
如果你只需要时间部分(你不关心天数):
df['timediff']=pd.to_datetime(df['timediff'].dt.total_seconds(),unit='s').dt.time
df
的输出:
time time2 timestart timediff
0 09:00:00 1900-01-01 09:00:00 1900-01-01 09:00:00 0 days 00:00:00
1 10:10:00 1900-01-01 10:10:00 1900-01-01 09:00:00 0 days 01:10:00
2 11:08:00 1900-01-01 11:08:00 1900-01-01 09:00:00 0 days 02:08:00
3 12:12:00 1900-01-01 12:12:00 1900-01-01 09:00:00 0 days 03:12:00