2

I have two UNIX timestamps that have distance in seconds D, where D = end - start. I want to find how many of these D seconds belong to an another time window [start2, end2], i.e. how many seconds intersect. Obviously it is not time2 - time1.

For example

start timestamp 1621707530 is Saturday, May 22, 2021 6:18:50 PM (GMT) end timestamp 1621736330 is Sunday, May 23, 2021 2:18:50 AM (GMT) How to find (preferably in Python) how many seconds between 01:00 AM and 02:00 AM belong to my [start, end] window?

For example interval [09:00 AM, 10:00 AM] does not intersect with [01:00 AM,02:00 AM], however interval [00:55 AM,01:03 AM] intersects for 3 minutes, or 180 seconds.

My code so far:

from datetime import datetime
from collections import namedtuple
Range = namedtuple('Range', ['start', 'end'])

r1 = Range(start=datetime(2021, 5, 22, 22, 23, 00),
           end=datetime(2021, 5, 23, 2, 1, 2))
r2 = Range(start=datetime(2021, 5, 23, 1, 0, 00),
           end=datetime(2021, 5, 23, 2, 0, 00))
latest_start = max(r1.start, r2.start)
earliest_end = min(r1.end, r2.end)
delta = (earliest_end - latest_start).seconds
overlap = max(0, delta)
print(overlap)

Can it be done with a simpler method?

fski51
  • 35
  • 4
  • I think this is about as good as it gets. Any more optimization might be difficult since in-builts are used. – Prometheus May 23 '21 at 10:07
  • @Prometheus it does not work well when the intervals don't overlap. It works if the intervals overlap. – fski51 May 23 '21 at 10:16
  • Then you must start with an if-statement to check if there is any overlap, if you think so. – Prometheus May 23 '21 at 10:19
  • 1
    source of OPs example for reference [Efficient date range overlap calculation in python?](https://stackoverflow.com/q/9044084/10197418) – FObersteiner May 23 '21 at 11:06

1 Answers1

0

Based on the answer: https://stackoverflow.com/a/46992092/14265469

The condition if (r1.start <= r2.end) and (r2.start <= r1.end): works surprisingly well:

from datetime import datetime
from collections import namedtuple

Range = namedtuple('Range', ['start', 'end'])

r1 = Range(start=datetime(2021, 5, 22, 22, 23, 20), 
             end=datetime(2021, 5, 22, 22, 23, 55))
r2 = Range(start=datetime(2021, 5, 22, 22, 23,  0), 
             end=datetime(2021, 5, 22, 22, 23, 25))

delta = "No overlapping"

if (r1.start <= r2.end) and (r2.start <= r1.end):
    latest_start = max(r1.start, r2.start)
    earliest_end = min(r1.end, r2.end)
    delta = (earliest_end - latest_start).seconds

print(delta) # 5
Yuri Khristich
  • 13,448
  • 2
  • 8
  • 23