Your problem is a scheduling problem. It has been well studied in operations research [1] / mathematical optimization [2].
Basically, you formulate your problem as a integer programming model [3] and use a solver [4] to solve it. You should check PuLP [5].
You can also ask your question at OR Exchange [6].
[1] https://en.wikipedia.org/wiki/Operations_research
[2] https://en.wikipedia.org/wiki/Mathematical_optimization
[3] https://en.wikipedia.org/wiki/Integer_programming
[4] https://en.wikipedia.org/wiki/List_of_optimization_software