-1

Im trying to check two things:

  1. If the time is between a specified interval.
  2. And if the current day is a weekday.

I have found this code from this thread:

from datetime import datetime, time

def is_time_between(begin_time, end_time, check_time=None):
    # If check time is not given, default to current UTC time
    check_time = check_time or datetime.now().time() # datetime.utcnow().time()
    if begin_time < end_time:
        return check_time >= begin_time and check_time <= end_time
    else: # crosses midnight
        return check_time >= begin_time or check_time <= end_time

And it works fantastic!

But how to, regardless, return false if the day is on a saturday or sunday?

Adam
  • 1,231
  • 1
  • 13
  • 37
  • datetime.now().time() is a datetime.time object - which has no concept of day of the week. datetime.now() is a datetime.datetime object, which you can call the isoweekday() method on. If check_time is expecting a datetime.time object, there is no way of determining the day of week. – luthervespers Dec 13 '20 at 18:16

2 Answers2

1

You just need to add one more check of check_time.weekday()>=5 as in:

from datetime import datetime, time

def is_time_between(begin_time, end_time, check_time=None):
    # If check time is not given, default to current UTC time
    check_time = check_time or datetime.now() # datetime.utcnow().time()
    if check_time.weekday()>=5:
        return False
    elif begin_time < end_time:
        return check_time >= begin_time and check_time <= end_time
    else: # crosses midnight
        return check_time >= begin_time or check_time <= end_time

P.S. To check for the weekday date information is vital which is not present in datetime.now().time(). You might want to use datetime.now() instead.

Hamza
  • 5,373
  • 3
  • 28
  • 43
0

You can use the function weekday() in order to retrieve the weekday of the given date. If it the returned value is 5 or 6 it means that it is saturday or sunday.

You can find more information here: https://docs.python.org/3/library/datetime.html#datetime.datetime.weekday

zanseb
  • 1,275
  • 10
  • 20