Run command only between certain times, else run other command
What I'm trying to do is change my wallpaper between certain times. For example, I have a wallpaper that I use at home, and a wallpaper that I use at school (this is a laptop). What I'd like to do is have a python script that runs a shell command that sets my wallpaper only when it is a weekday and when the time is between 08:00 and 14:15.
I'm using python 3.13 and arch linux. The part I'm having trouble on is finding the day of the week, and comparing the time. I know how to run the shell command through python(os.s开发者_Python百科ystem('command')).
import datetime
day_of_week = datetime.date.today().weekday() # 0 is Monday, 6 is Sunday
time = datetime.datetime.now().time()
if day_of_week < 5 and (time > datetime.time(8) and time < datetime.time(14,15)):
do_something()
Wooble's answer is right. If you want a slightly less efficient version but without having to remember the index of each day, you can use the weekday name (assuming your local is english):
import datetime
week_day = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
today = datetime.date.today()
now = datetime.datetime.now().time()
def change_wallpaper():
print "Changed!"
if today.strftime("%A") in week_day and (now > datetime.time(8) and now < datetime.time(14,15)):
change_wallpaper()
精彩评论