我有以下两个时间栏," Time1"和"时间2"。我必须计算"差异"列,在Pandas中是(Time2-Time1):
Time1 Time2 Difference
8:59:45 9:27:30 -1 days +23:27:45
9:52:29 10:08:54 -1 days +23:16:26
8:07:15 8:07:53 00:00:38
当Time1和Time2处于不同时间时,我得到结果为" -1天+"我的前两个值的所需输出如下:
Time1 Time2 Difference
8:59:45 9:27:30 00:27:45
9:52:29 10:08:54 00:16:26
如何在Pandas中获得此输出?
两个时间值都在< datetime64 [ns]' D型。
答案 0 :(得分:3)
问题不在于time1
和time2
在不同时段,time2
在time1
之前,因此time2-time1
是否定的,这是如何存储负时间值。如果您只想将分钟差异作为负数,则可以在计算差异之前提取分钟数:
(df.Time1.dt.minute- df.Time2.dt.minute)
答案 1 :(得分:2)
我无法使用pandas 17.1重现这个问题:
import pandas as pd
d = {
"start_time": [
"8:59:45",
"9:52:29",
"8:07:15"
],
"end_time": [
"9:27:30",
"10:08:54",
"8:07:53"
]
}
from datetime import datetime
df = pd.DataFrame(data=d)
df['start_time'] = pd.to_datetime(df['start_time'])
df['end_time'] = pd.to_datetime(df['end_time'])
df.end_time - df.start_time
0 00:27:45
1 00:16:25
2 00:00:38
dtype: timedelta64[ns]