I have a Python script that I need to run every two weeks on my Raspberry Pi, I thought it would be simple enough to use a Cron job to schedule the script. It turns out that configuring a job to run ever 2 weeks isn’t as simple as I initially thought. I found some solutions to this here and planned to use the second approach (which uses a test statement).
This got me thinking that I can probably incorporate some form of test within the Python script itself, my plan was to schedule the script to run weekly, but include some logic within the Python script that means that it will only run on even numbered weeks.
I came up with this solution:
import datetime
if isinstance((datetime.datetime.now().isocalendar().week / 2),int):
DoStuff()
This does the following
- Get the current week of the year (datetime.datetime.now().isocalendar().week)
- Divides the week number returned by 2
- Uses isinstance to check if the value returned is an integer (which would be an even week)
- If the value is an integer execute the method DoStuff() – which is the main method within my script
- If the value isn’t an integer – do nothing
Note: If you replace int with float this will cause the DoStuff() method to execute on odd numbered weeks.

Leave a comment