python时间间隔算法总和

编程入门 行业动态 更新时间:2024-10-23 15:33:45
本文介绍了python时间间隔算法总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有2个时间间隔,例如16:30-20:00和15:00-19:00,我需要找到这两个间隔之间的总时间,所以结果是5小时(我将两个间隔都加了并减去相交的间隔),如何编写一个通用函数,该函数还处理所有情况,例如一个间隔在另一个间隔之内(因此结果是较大间隔的间隔),没有交集(因此结果是两者之和)间隔).

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).

我的传入数据结构是原始的,只是像"15:30"这样的字符串,因此可能需要进行转换.

My incoming data structure is primitive, simply string like "15:30" so a conversion may be needed.

谢谢

推荐答案

from datetime import datetime, timedelta START, END = xrange(2) def tparse(timestring): return datetime.strptime(timestring, '%H:%M') def sum_intervals(intervals): times = [] for interval in intervals: times.append((tparse(interval[START]), START)) times.append((tparse(interval[END]), END)) times.sort() started = 0 result = timedelta() for t, type in times: if type == START: if not started: start_time = t started += 1 elif type == END: started -= 1 if not started: result += (t - start_time) return result

用问题中的时间进行测试:

Testing with your times from the question:

intervals = [ ('16:30', '20:00'), ('15:00', '19:00'), ] print sum_intervals(intervals)

打印:

5:00:00

与不重叠的数据一起对其进行测试

Testing it together with data that doesn't overlap

intervals = [ ('16:30', '20:00'), ('15:00', '19:00'), ('03:00', '04:00'), ('06:00', '08:00'), ('07:30', '11:00'), ] print sum_intervals(intervals)

结果:

11:00:00

更多推荐

python时间间隔算法总和

本文发布于:2023-11-29 08:39:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645895.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:总和   间隔   算法   时间   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!