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?