python - 从另一个时间字符串中减去一个时间字符串
问题描述
我有一列存储两个不同的时间:
Beginning | End
17:05 | 17:10
我希望能够得到两者之间的区别。
现在,两列都存储为字符串。如何将它们转换为对时间戳聚合友好的数据类型?
解决方案
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
)
推荐阅读
- solr - Solr按每个单词的开头搜索
- javascript - 寻找一种基于另一个项目的 ID 来选择类的方法
- android - Android 自定义 lint 规则未检测到任何问题(对于导入)
- javascript - 函数和箭头 (=>) 函数之间有区别吗
- linux - 如何为 .sh 文件制作 .desktop 文件
- cassandra - 在 Cassandra 中插入多次后出现无效或不支持的协议版本错误
- excel - 尝试根据数据移动整行
- java - JSP 导入中的上下文路径
- c# - 具有标签的 DataRows 的自定义 DataTable
- php - Laravel 中的 AJAX 函数未将表单数据发布到控制器