I am programming in Python and using SQLAlchemy开发者_如何学编程 to store business hours.
The business hours are composed of three parts:- The days of the week stored in binary as a bitmask
- the time the business opens,
- the time the business closes.
The bitmask works like this. There are 7 digits, which are either 0 or 1, which will represent different sequences of weekdays. Each position represents a day of the week. The first position stands for Monday and the last for Sunday. For example, 1111100 represents Monday-Friday, and 0000111, Friday-Saturday. Also, I am storing the hours in military time, 0600 meaning 6AM and 1800 meaning 6PM.
hours = Table('hours', Base.metadata,
Column("id", Integer, primary_key=True),
Column("businessid", Integer, ForeignKey('businesses.id')),
Column("days", Integer),
Column("open", Integer),
Column("close", Integer),
)
class Hours(object):
def __init__(self, days=None, open=None, close=None):
self.days = days
self.open = open
self.close = close
mapper(Hours, hours)
mapper(Business, businesses, properties={
'hours': relationship(Hours, backref='business'),
})
What is the Pythonic way to figure out when two of the bitmasks representing the days of the week overlap? And also, what is the best way to find out if a business is currently open when given two pairs of Hours objects?
As far as checking days of the week, if by binary you mean a string of the form '1011011':
overlap = [n for n in range(7) if (bitmask1[n] == bitmask2[n] == '1')]
will give you a list of the numbers (from 0-6) of the overlapping days -- [4] for Friday overlapping.
overlap = ''.join(('1' if (bitmask1[n] == bitmask2[n] == '1') else '0') for n in range(7))
Will give you a new bitmask string -- '00000100' for Friday overlapping.
If you're actually storing the number as an integer, it's probably easiest to just convert it to one, either with bin(bitmask)[2:]
or "{0:b}".format(bitmask)
.
I'm not sure what you mean by "currently open ... two pairs of hours objects". Do you want the overlap of the two pairs of hours? If they are whole hours, its easy:
[hour for hour in range(firsthour, secondhour) if hour in range(openinghour, closinghour)
Will give you a list of the hours in both ranges.
精彩评论