In python how do I check if its a weekday (Monday - Friday) and the time is between 10 AM to 3 PM?
-
3your previous question has an answer containing code that you're asking here for! not to mention that you're just duplicating that question stackoverflow.com/questions/1902338/…– SilentGhostDec 15, 2009 at 12:59
-
Sorry but the earlier solution was voted -ve– VishalDec 15, 2009 at 14:57
-
so what? does it somehow stop code from running?– SilentGhostDec 15, 2009 at 15:24
-
3@SilentGhost, to be fair, I can't see that the question you mention has any code that addresses the time part of the question, only the date. And crudely at that. And that question looked to be more focused on how to do the background work, while this is actually a better, more focused question.– Peter HansenDec 16, 2009 at 2:08
3 Answers
>>> import datetime
>>> d = datetime.datetime.now()
# => datetime.datetime(2009, 12, 15, 13, 50, 35, 833175)
# check if weekday is 1..5
>>> d.isoweekday() in range(1, 6)
True
# check if hour is 10..15
>>> d.hour in range(10, 15)
True
# check if minute is 30
>>> d.minute==30
False
-
2The hour check should be
d.hour in range(10, 15)
. If the hour equals 15, it's past 3 PM, so we shouldn't include 15 in the range of allowed hours. Dec 15, 2009 at 13:00 -
-
1For checking in range 9.30AM to 3.30PM: d.hour*60+d.minute in range(9*60+30, 15*60+30) Dec 15, 2009 at 14:25
-
-
>>> import datetime
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2009, 12, 15, 12, 45, 33, 781000)
>>> now.isoweekday()
2 # Tuesday
time between 10 a.m. and 3 p.m. is right there as well
https://docs.python.org/2/library/datetime.html
The documentation states that date.weekday()
returns the day of the week as an integer, where Monday is 0 and Sunday is 6. So this code will work:
import datetime
# Hours must be 24 hour clock times
def is_weekday_and_time_in_range(date, start_hour, end_hour):
return date.weekday() < 5 and date.hour in range(start_hour, end_hour)
today = datetime.datetime.now()
is_weekday_and_time_in_range(today, 10, 15)