mcfly
mcfly

Reputation: 1151

Python and check if current datetime is in specific range

I am trying to do something similar to this, but i want to specify the start date and end date by actual weekday names and times. For example, I want to check if the current datetime (datetime.datetime.now()) is in between Tuesday at 4:30pm and Thursday at 11:45am. This would update weekly so it has to be by Tuesday/Thursday mentality.

I have thought about how to do the weekdays (but i don't know how to wrap the time part into it):

TimeNow = datetime.datetime.now()

if TimeNow.weekday() >= 1 and TimeNow.weekday() <= 3:
    #runcodehere

Any thoughts on how i would do this?

Upvotes: 0

Views: 503

Answers (3)

O. Rose
O. Rose

Reputation: 61

It's not very neat but something like this should work:

TimeNow = datetime.datetime.now()

if (TimeNow.weekday() == 1 and ((TimeNow.hour() == 4 and TimeNow.minute >= 30) or TimeNow.hour > 4)) or (TimeNow.weekday() == 2) or (TimeNow.weekday() == 3 and (TimeNow.hour() < 11 or (TimeNow.hour() == 11 and TimeNow.minute <= 45)):
     #runcodehere

Upvotes: 2

scytale
scytale

Reputation: 12641

Neatest way is to use the amount of minutes elapsed in a week:

def mins_in_week(day, hour, minute):
    return day * 24 * 60 + hour * 60 + minute

if (mins_in_week(1, 16, 30) < 
    mins_in_week(TimeNow.weekday(), TimeNow.hour, TimeNow.minute) < 
    mins_in_week(3, 11, 45)):
    ....

Upvotes: 4

tmdavison
tmdavison

Reputation: 69056

You can use a combination of and and or, and have different conditions for each day:

import datetime

TimeNow = datetime.datetime.now()

day_now = TimeNow.weekday()
time_now = TimeNow.hour*60 + TimeNow.minute

if (day_now == 1 and time_now > 990) or (day_now == 2) or (day_now == 3 and time_now < 705):
    # do something

Upvotes: 0

Related Questions