I am playing with python code for looking at my work rota. I have made a nice script which reads the rota document sent to me and extracts all of my shifts into datetimes for shift start and end, it can also reformat them into google calendar events which is great for automating my calendar.
I now want to look at my rota and compare it against the contractual rules for my rota pattern.
The rule I am looking at presently is: "no more than 72 hours of work in any 7 day period"
Now, this is very easy to look at each week and calculate how many hours are worked. I have made this work as below:
def hours_per_week(df):
df["Week Start"] = pd.to_datetime(df["Start Date"]) - pd.to_timedelta(7, unit="d")
df = (
df.groupby([pd.Grouper(key="Week Start", freq="W-MON")])["Shift Length"]
.sum()
.reset_index()
.sort_values("Week Start")
)
df = df.rename(columns={"Shift Length": "Hours"})
df["Hours"] = df["Hours"] / np.timedelta64(1, "h")
return df
However, this method calculates the hours in the 7 day period from 0000 every Monday. The rule applies to ANY 7 day period so from 0500 on a Wednesday would be equally relevant as from 0000 on Monday.
The only way I can think of doing this is by iterating through EVERY possible hour working out the hours worked in the 7 day period from that hour. This would be easy enough but seems hugely inefficient. Before I go about writing this ugly piece of code, does anyone have an idea of a better approach to this problem?