How to change this code so it skips weekends but starts on Tuesday

Viewed 65

In a previous question of mine, I asked how to do the following in python (this is a summary):

I'm creating an automation in Python, that will automatically navigate to my school's website, and join the online class, etc using selenium. I've completely finished that part, and it all works perfectly. Now, I'm trying to figure out how to schedule these actions.

I have 10 classes in total. I have 6 classes in a day. My school week goes from Monday and Friday. In my timetable, there are a total of 6 days, meaning that every week, one day in the timetable gets rotated out, and I don't have it that week, and another rotates in.


So, to further explain what I mean by that, in the first week, I would have Days 1-5 Monday to Friday, but I would not have Day 6. I would have Day 6 the following Monday.

How do I go about scheduling these days (Day1 - Day6) so that they run on Monday to Friday with one day rotating out and then back in the next week (as I described above)?

This was the answer I got, which was exactly what I needed, however, it only works if first_day_of_school is on a monday.

from datetime import datetime

day_of_year = datetime.now().timetuple().tm_yday
first_day_of_school = datetime(2020, 9, 15).timetuple().tm_yday
day_of_school = day_of_year - first_day_of_school
week_of_school = day_of_school // 7
day_of_week = day_of_school % 7 # 0 means Monday
day_of_term = week_of_school * 5 + day_of_week
class_index = day_of_term % 6
print(class_index)

What I would like to know is, how can I correctly modify this so it works in the same way, if first_day_of_school is on a tuesday?

I understand that the // 7 and * 5 parts are how weekends are skipped if it's on a Monday, but I can't work out the math to get it to work with another day. I've tried so many different combinations over the last 12 hours and I can't solve it. I really hope the answer's not just staring me in the face cos this has really frustrated me.

I've tried working it out backwards and forwards and nothing is working. This aspect of Python is very new to me.

1 Answers

I think timedelta is what you are looking for

import datetime

day_of_year = datetime.datetime.now().timetuple().tm_yday

skip_days = 2
delta = datetime.timedelta(days=skip_days)
first_day_of_school = datetime.datetime(2020, 9, 15) + delta

first_day_of_school = first_day_of_school.timetuple().tm_yday
day_of_school = day_of_year - first_day_of_school
week_of_school, day_of_week = divmod(day_of_school, 7) 
day_of_term = week_of_school * 5 + day_of_week
class_index = day_of_term % 6
print(class_index)
Related