首页 > 解决方案 > 从另一个时间字符串中减去一个时间字符串

问题描述

我有一列存储两个不同的时间:

Beginning  |   End
  17:05    |  17:10

我希望能够得到两者之间的区别。

现在,两列都存储为字符串。如何将它们转换为对时间戳聚合友好的数据类型?

标签: pythonpandas

解决方案


You can use pd.to_datetime with the format %H:%M, then subtract the two:

df['Time_Difference'] = pd.to_datetime(df['End'], format='%H:%M') - pd.to_datetime(df['Beginning'], format='%H:%M')

>>> df
  Beginning    End Time_Difference
0     17:05  17:10        00:05:00

Or if you actually want to change the Beginning and End columns, you can do something like:

df[['Beginning', 'End']] = df[['Beginning', 'End']].apply(lambda x: pd.to_datetime(x, format='%H:%M'))
df['Time_Difference'] = df['End'] - df['Beginning']

>>> df
            Beginning                 End Time_Difference
0 1900-01-01 17:05:00 1900-01-01 17:10:00        00:05:00

But the default date will be added (1900-01-01)


推荐阅读