westbyb
westbyb

Reputation: 181

Create Range of Hours in Python

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!

Upvotes: 2

Views: 8384

Answers (4)

bereal
bereal

Reputation: 34252

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

Upvotes: 2

user1202136
user1202136

Reputation: 11547

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

Upvotes: 1

Fred Larson
Fred Larson

Reputation: 62053

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

Upvotes: 2

Abhranil Das
Abhranil Das

Reputation: 5918

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.

Upvotes: 1

Related Questions