Search code examples
pythonalgorithmpython-2.7optimizationpython-datetime

List of datetimes with the context of working hours, calculate non working hours


So I have a set of working times (shifts), i.e. a tuple of start and end points in datetime format. One person then is able to have multiple shifts on the same day:

from datetime import datetime
shift1_1 = datetime(year=2019, month=8, day=21, hour=8)
shift1_2 = datetime(year=2019, month=8, day=21, hour=11)
shift2_1 = datetime(year=2019, month=8, day=21, hour=12)
shift2_2 = datetime(year=2019, month=8, day=21, hour=17)
shift3_1 = datetime(year=2019, month=8, day=22, hour=8)
shift3_2 = datetime(year=2019, month=8, day=22, hour=10)
shift4_1 = datetime(year=2019, month=8, day=22, hour=12)
shift4_2 = datetime(year=2019, month=8, day=22, hour=15)
shift5_1 = datetime(year=2019, month=8, day=22, hour=17)
shift5_2 = datetime(year=2019, month=8, day=22, hour=19)
shifts = [(shift1_1,shift1_2), (shift2_1,shift2_2), (shift3_1,shift3_2), (shift4_1,shift4_2),(shift5_1,shift5_2)]

I would like to calculate the complement, so start and end points of non working hours.

How would one tackle this problem? As for right now, I did not find a practical method of calculation. Does anybody know an algorithm for this problem?

I would be grateful for any hint in the right direction.


Solution

  • I figured it out with the help of the post of tituszban

    I generate a list of days I have in my list of shifts. Then I loop over all my shifts and split them up into a list of single datetimes. For each day I then:

    • create an empty list
    • create one datetime object each for beginning and end of the given day
    • add beginning of the day
    • filter my list of single datetimes of shifts to match given day and loop over this filter, adding the datetimes to my list
    • using pairwise iteration I can create new tuples and add them to off_times list

    In the end I get a new array of tuples containing my off_times.