0

I have two time ranges in python and I would like to find whether there is any overlap between them or not. I am looking for an algorithm for that. For instance I have the following time ranges:

r1 = start=(15:30:43), end=(16:30:56)
r2 = start=(15:40:35), end=(15:50:20)

How can I find the overlap among them in python?

Dirk Herrmann
  • 5,550
  • 1
  • 21
  • 47
user1993
  • 97
  • 1
  • 3
  • 9
  • https://stackoverflow.com/questions/9044084/efficient-date-range-overlap-calculation-in-python – Mojtaba Kamyabi Mar 11 '19 at 20:19
  • 1
    Welcome to StackOverflow! Please read the post on [how to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) and also the [how do I ask a good question guide](https://stackoverflow.com/help/how-to-ask). Having done that, please improve your question by adding a proper example and showing us what you've tried so far. :-) – elemakil Mar 11 '19 at 20:19
  • 2
    Possible duplicate of [Efficient date range overlap calculation in python?](https://stackoverflow.com/questions/9044084/efficient-date-range-overlap-calculation-in-python) – elemakil Mar 11 '19 at 20:20

1 Answers1

1

You could use DatetimeIndex objects from the pandas package as follows:

import pandas as pd


# create DatetimeIndex objects with *seconds* resolution
dtidx1 = pd.date_range('15:30:43', '16:30:56', freq='S')
dtidx2 = pd.date_range('15:40:35', '15:50:20', freq='S')

# use the DatetimeIndex.intersection method to get another 
# DatetimeIndex object whose values are what you requested
dtidx1.intersection(dtidx2)
jeschwar
  • 1,286
  • 7
  • 10
  • Would not recommend suggesting packages that OP did not specify they were using in an answer. Also, this specifically quantizes down to seconds, which may or may not be desired. – alkasm Mar 11 '19 at 20:37