python时间间隔算法求和

发布于 2024-08-02 23:34:58 字数 226 浏览 3 评论 0原文

假设我有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

梦开始←不甜 2024-08-09 23:34:58
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

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

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

打印:

5:00:00

与不重叠

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

That prints:

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)

result:

11:00:00
喵星人汪星人 2024-08-09 23:34:58

我假设您可以自行转换为 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.

山田美奈子 2024-08-09 23:34:58

存在重叠时的代码,请将其添加到您的解决方案之一:

def interval(i1, i2):
    minstart, minend = [min(*e) for e in zip(i1, i2)]
    maxstart, maxend = [max(*e) for e in zip(i1, i2)]

    if minend < maxstart: # no overlap
        return minend-minstart + maxend-maxstart
    else: # overlap
        return maxend-minstart

Code for when there is an overlap, please add it to one of your solutions:

def interval(i1, i2):
    minstart, minend = [min(*e) for e in zip(i1, i2)]
    maxstart, maxend = [max(*e) for e in zip(i1, i2)]

    if minend < maxstart: # no overlap
        return minend-minstart + maxend-maxstart
    else: # overlap
        return maxend-minstart
柳若烟 2024-08-09 23:34:58

您需要将字符串转换为日期时间。您可以使用datetime.datetime.strptime来完成此操作。

给定 datetime.datetime 对象的间隔,如果间隔是:

int1 = (start1, end1)
int2 = (start2, end2)

那么它不就是:

if end1 < start2 or end2 < start1:
    # The intervals are disjoint.
    return (end1-start1) + (end2-start2)
else:
    return max(end1, end2) - min(start1, start2)

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:

int1 = (start1, end1)
int2 = (start2, end2)

Then isn't it just:

if end1 < start2 or end2 < start1:
    # The intervals are disjoint.
    return (end1-start1) + (end2-start2)
else:
    return max(end1, end2) - min(start1, start2)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文