English 中文(简体)
p日物体清单中的超时
原标题:Find spare time in list of python datetime objects

我有一份活动清单。 每一活动作为起点和终点,均为时标。 我现在想到一份“零星时间”活动清单,这些活动是在现有活动之外为展示而创造的。 我希望这一点是有意义的。 这是我迄今能够取得的最佳结果。 任何帮助都值得赞赏。

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

最佳回答

我将采取更多这样的方式——只是给你更多的概念(它需要更多的错误处理,但现在它应该只是表明想法):

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()
问题回答

暂无回答




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签