thombashi / DateTimeRange

DateTimeRange is a Python library to handle a time range. e.g. check whether a time is within the time range, get the intersection of time ranges, truncate a time range, iterate through a time range, and so forth.
https://datetimerange.rtfd.io/
MIT License
106 stars 16 forks source link

Intersect multiple date time range #37

Closed tgsimo92 closed 3 years ago

tgsimo92 commented 3 years ago

How can i intersect multiple date time range?

thombashi commented 3 years ago

@tgsimo92 You can call intersection method combined with functools.reduce method. For example:

from functools import reduce
from datetimerange import DateTimeRange

ranges = [
    DateTimeRange("2021-01-01T10:00:00+0900", "2021-01-01T10:10:00+0900"),
    DateTimeRange("2021-01-01T10:01:00+0900", "2021-01-01T10:10:00+0900"),
    DateTimeRange("2021-01-01T10:00:00+0900", "2021-01-01T10:09:00+0900"),
]
print(reduce(lambda lhs, rhs: lhs.intersection(rhs), ranges))
2021-01-01T10:01:00+0900 - 2021-01-01T10:09:00+0900