python中日期时间列表的索引估计

时间:2013-06-06 05:30:44

标签: python function datetime

所以我有一个带有以下内容的函数:times =日期时间对象列表,start =日期时间对象,end =日期时间对象。并返回一个列表,其中的日期时间对象介于开始和结束

之间
def func(times,start,end):
    return times[start:end],(times.index(start),times.index(end))

如果start和/或end实际上不在日期时间对象列表中,我需要它才能工作:times

因此,如果start不在列表中,则第一个项目将“大于”start,如果end不在{{1}}中,则会执行相同操作列表,除了它将“小于”。

获得实际起点终点的指数也很重要。

我会为我的功能添加什么?

3 个答案:

答案 0 :(得分:1)

您可以使用bisect

import bisect
def func(times, start, end):
    bucket = [start, end]
    out = [x for x in times if bisect.bisect(bucket, x) is 1 or x in bucket]
    return out, (times.index(out[0]), times.index(out[-1]))

答案 1 :(得分:0)

这个问题的天真方法:

def func(times, start, end):
    s = 0
    e = len(times)-1

    while s < len(times) and times[s]< start: 
        s+=1

    while e >= 0 and times[e] > end: 
        e-=1

    if (e < 0 or s >= len(times) or s > e): 
        return None

    return times[s:e+1], (s,e)

答案 2 :(得分:-1)

为什么不简单地[dt for dt in times if dt >= start and dt <= end]