limp_chimp
limp_chimp

Reputation: 15163

How to check in python if I'm in certain range of times of the day?

I want to check in python if the current time is between two endpoints (say, 8:30 a.m. and 3:00 p.m.), irrespective of the actual date. As in, I don't care what the full date is; just the hour. When I created datetime objects using strptime to specify a time, it threw in a dummy date (I think the year 1900?) which is not what I want. I could use a clumsy boolean expression like (hour == 8 and minute >= 30) or (9 <= hour < 15) but that doesn't seem very elegant. What's the easiest and most pythonic way to accomplish this?

Extending a bit further, what I'd really like is something that will tell me if it's between that range of hours, and that it's a weekday. Of course I can just use 0 <= weekday() <= 4 to hack this, but there might be a better way.

Upvotes: 9

Views: 24667

Answers (4)

Henry Keiter
Henry Keiter

Reputation: 17168

datetime objects have a method called time() which returns a time object (with no date information). You can then compare the time objects using the normal < or > operators.

import datetime
import time
timestamp = datetime.datetime.now().time() # Throw away the date information
time.sleep(1)
print (datetime.datetime.now().time() > timestamp) # >>> True (unless you ran this one second before midnight!)

# Or check if a time is between two other times
start = datetime.time(8, 30)
end = datetime.time(15)
print (start <= timestamp <= end) # >>> depends on what time it is

If you also want to check for weekdays, the code you suggest is probably the most effective way to go about it, but in that case you probably don't want to throw out the original datetime object.

now = datetime.datetime.now()
if 0 <= now.weekday() <= 4:
    print ("It's a weekday!")
print (start <= now.time() <= end) # with start & end defined as above

Upvotes: 22

Fred Mitchell
Fred Mitchell

Reputation: 2161

I don't know how you are getting your start and end time, but if you are limiting it to a single day, then be sure that the start time comes before the end time. If you had, for example, start time = 1800 and end time = 1200, you won't find any time in between on that day.

Upvotes: 0

alecxe
alecxe

Reputation: 473863

>>> import datetime
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2013, 9, 19, 3, 39, 38, 459765)
>>> 0 <= now.weekday() <= 4
True
>>> datetime.time(hour=8, minute=30) <= now.time() <= datetime.time(hour=15)
False

Upvotes: 2

Tim Peters
Tim Peters

Reputation: 70592

from datetime import datetime, time
now = datetime.now()
if 0 <= now.weekday() <= 4:
    print "it's a weekday"
    if time(8, 30) <= now.time() <= time(15):
        print "and it's in range"

Upvotes: 2

Related Questions