Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 463
limp_chimp Avatar asked Sep 18 '13 23:09

limp_chimp


3 Answers

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
like image 98
Henry Keiter Avatar answered Nov 14 '22 21:11

Henry Keiter


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"
like image 45
Tim Peters Avatar answered Nov 14 '22 21:11

Tim Peters


>>> 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
like image 44
alecxe Avatar answered Nov 14 '22 22:11

alecxe