pythondatetimedate-comparison

Comparing time of day on day of week to time of day on day of week


Is there a straightforward way to test whether now is between Friday, 5pm and Sunday, 5pm, of the same week?

This attempt returns False because it does not compare now.time() relative to either now.isoweekday() >= 5 or now.isoweekday() <= 7 being True first.

[in]:
import datetime
now = datetime.datetime.now()
print(now)
(now.isoweekday() >= 5 and now.time() >= datetime.time(17, 0, 0, 0)) and (now.isoweekday() <= 7 and now.time() <= datetime.time(17, 0, 0, 0))

[out]:
2022-12-17 10:00:32.253489

False

Solution

  • Essentially the condition you're looking for is: after 5pm on Friday, any time Saturday, or before 5pm on Sunday. That's easy to express:

    (now.isoweekday() == 5 and now.time() >= datetime.time(17, 0, 0, 0)
        or now.isoweekday() == 6
        or now.isoweekday() == 7 and now.time() <= datetime.time(17, 0, 0, 0)
    )
    

    The other option would be something like:

    but I think that's actually more complicated than the above if you're just testing this one condition; an approach like that would make more sense if it was part of a repeated pattern.