2

So I'm looking to take input such as 7:00 AM as a start time, and say, 10:00 PM as an endtime, and then compare a set of times (also in the form of 8:00 AM, 3:00 PM, etc) to see if those time are or aren't in the range of time. Is there a good way to create a "day" that has a range of hours (the endtimes can be as late as 4:00 AM, so I was figuring I would go from 6:00 AM - 5:59 AM instead of midnight - 11:59 PM, if that's possible) that I can check times against?

For example: starttime = 8:00 AM, endtime = 3:00 AM, and checking time = 7:00 AM would return time as being out of the range.

Thanks!

0

4 Answers 4

2

Use datetime parsing and comparison capabilities:

from datetime import datetime, timedelta

def parse_time(s):
    ''' Parse 12-hours format '''
    return datetime.strptime(s, '%I:%M %p')

starttime = parse_time('8:00 AM')
endtime   = parse_time('3:00 AM')
if endtime < starttime:
   # add 1 day to the end so that it's after start
   endtime += timedelta(days=1)

checked_time = parse_time('7:00 AM')

# Can compare:
print starttime <= checked_time < endtime
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this should solve my problem of the 3:00 AM being after 8:00 AM.
2

I'd probably use the datetime library. Use strptime() on your input strings, then you can compare the datetime objects directly.

Comments

1

Convert all times into a 24-hour format, taking minutes and seconds as fractions of hours, then just compare them as numbers to see if a time lies in an interval.

Comments

1

Python's datetime.* classes already support comparison:

>>> import datetime
>>> datetime.datetime(2012,10,2,10) > datetime.datetime(2012,10,2,11)
False
>>> datetime.datetime(2012,10,2,10) > datetime.datetime(2012,10,2,9)
True

So all you have to do is declare a class TimeRange, with two members startTime and endTime. Then a "inside" function can be as simple as:

def inside(self, time):
    return self.startTime <= time and time <= self.endTime

1 Comment

Actually, comparison is even easier than that in Python: self.startTime <= time <= self.endTime.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.