24

In python how do I check if its a weekday (Monday - Friday) and the time is between 10 AM to 3 PM?

4
  • 3
    your 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/… Dec 15, 2009 at 12:59
  • Sorry but the earlier solution was voted -ve
    – Vishal
    Dec 15, 2009 at 14:57
  • so what? does it somehow stop code from running? Dec 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. Dec 16, 2009 at 2:08

3 Answers 3

39
>>> 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
5
  • 2
    The 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
  • How do we go if the time range is 9:30 AM to 3:30 PM?
    – Vishal
    Dec 15, 2009 at 13:22
  • 1
    For checking in range 9.30AM to 3.30PM: d.hour*60+d.minute in range(9*60+30, 15*60+30)
    – Nick Moore
    Dec 15, 2009 at 14:25
  • isoweekday is actually a function so it needs to be isoweekday()
    – Dan P.
    May 15, 2013 at 18:40
  • @DanielPatz, wow, a three year old typo - thanks for spotting!
    – miku
    May 15, 2013 at 20:26
1
>>> 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

0

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)

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.