python时间间隔算法求和
假设我有 2 个时间间隔,例如 16:30 - 20:00 和 15:00 - 19:00,我需要找到这两个时间间隔之间的总时间,因此结果是 5 小时(我将两个时间间隔相加并减去相交间隔),如何编写一个通用函数来处理所有情况,例如一个间隔在另一个间隔内(因此结果是较大间隔的间隔),没有交集(因此结果是两个间隔的总和)。
我传入的数据结构是原始的,只是像“15:30”这样的字符串,因此可能需要转换。
谢谢
Assume I have 2 time intervals,such as 16:30 - 20:00 AND 15:00 - 19:00, I need to find the total time between these two intervals so the result is 5 hours (I add both intervals and subtract the intersecting interval), how can I write a generic function which also deals with all cases such as one interval inside other(so the result is the interval of the bigger one), no intersection (so the result is the sum of both intervals).
My incoming data structure is primitive, simply string like "15:30" so a conversion may be needed.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
用问题中的时间进行测试:
打印:
与不重叠
结果的数据一起测试它:
Testing with your times from the question:
That prints:
Testing it together with data that doesn't overlap
result:
我假设您可以自行转换为 datetime 之类的内容。
将两个间隔相加,然后减去任何重叠部分。您可以通过比较两个范围中每个范围的最小值和最大值来获得重叠。
I'll assume you can do the conversion to something like datetime on your own.
Sum the two intervals, then subtract any overlap. You can get the overlap by comparing the min and max of each of the two ranges.
存在重叠时的代码,请将其添加到您的解决方案之一:
Code for when there is an overlap, please add it to one of your solutions:
您需要将字符串转换为日期时间。您可以使用
datetime.datetime.strptime
来完成此操作。给定
datetime.datetime
对象的间隔,如果间隔是:那么它不就是:
You'll want to convert your strings into datetimes. You can do this with
datetime.datetime.strptime
.Given intervals of
datetime.datetime
objects, if the intervals are:Then isn't it just: