我有一系列活动。作为Start和End的每个事件都是datetime对象。我现在想要一个“空闲时间”事件列表,它是根据现有事件创建的,用于显示目的。我希望这是有道理的。到目前为止,这是我能想到的最好的。任何帮助表示赞赏!
class Event():
Start = datetime.datetime
End = datetime.datetime
Reserved = boolean
# create a couple of events with some spare time between them...
ev1 = Event()
ev1.Start = datetime.datetime(2011,1,1,5)
ev1.End = datetime.datetime(2011,1,1,6)
ev1.Reserved = True
ev2 = Event()
ev2.Start = datetime.datetime(2011,1,1,8)
ev2.End = datetime.datetime(2011,1,1,9)
ev2.Reserved = True
events = [ev1,ev2]
# sort the events list...
events.sort(key=lambda e: e.Start)
# create a 'spare time' event based on the existing events...
allevents = []
for event in events:
spare = Event()
spare.Start = events[events.index(event)-1].End+datetime.timedelta(seconds=1)
spare.End = event.Start-datetime.timedelta(seconds=1)
spare.Reserved = False
allevents.append(spare)
allevents.append(event)
allevents.sort(key=lambda e: e.Start)
for event in allevents:
print str(event.Start), str(event.End), event.Reserved
所以,这有效,但我还没有弄清楚如何在午夜停止和开始业余时间,但在我这样做之前,我想知道我是否正朝着正确的方向前进。还是有更好的方法? (通常有!)..
MFB
答案 0 :(得分:1)
我会这样做更多 - 只是为了给你一些更多的概念(它需要更多的错误处理,但现在它应该只显示这个想法):
from datetime import datetime
class Venue(object):
"""Collection of events"""
def __init__(self):
self.events_list = []
def add_events(self,*args):
for e in args:
self.events_list.append(e)
def sort_list(self):
self.events_list.sort(key=lambda e: e.start_date)
def find_spare_times(self):
self.sort_list()
for event in self.events_list:
yield event.start_date
yield event.end_date
def add_spare_events(self):
l = list(self.find_spare_times())
print l
new_start,new_end = None, None
for e in l[1:]:
if new_start:
new_end = e
self.add_events(Event(new_start,new_end,res=False))
new_start = None
else:
new_start = e
new_end = None
def get_events(self):
return self.events_list
class Event(object):
"""Holds the data for an individual event"""
def __init__(self,start_date, end_date,res=True):
self.start_date = start_date
self.end_date = end_date
self.reserved = res
# create a couple of events with some spare time between them...
def main():
ev1 = Event(datetime(2011,1,1,5),datetime(2011,1,1,6))
ev2 = Event(datetime(2011,1,1,8),datetime(2011,1,1,9))
v = Venue()
v.add_events(ev1,ev2)
print v.get_events()
v.add_spare_events()
print v.get_events()
if __name__ == "__main__":
main()