reduce datetime list by timedelta
Question: in python, how I can reduce a datetime list by a timedelta neighborhood?

If I have

    
    
        dates = [
            dt.datetime(1970, 1, 1, 0, 2),
            dt.datetime(1970, 1, 1, 0, 3),
            dt.datetime(1970, 1, 1, 0, 7),
            dt.datetime(1970, 1, 1, 0, 8)
        ]
    

and a timedelta

    
    
    delta = dt.timedelta(minutes=2)
    

How I can get this ?

    
    
        expected = [
            dt.datetime(1970, 1, 1, 0, 2, 30),
            dt.datetime(1970, 1, 1, 0, 7, 30)
        ]
    

# EDIT

A example with numbers, if I have this number list

    
    
    numbers = [1,2,6,7]
    delta = 1
    

I try to group the nearly values and get a characteristic value (a central
value) of the group. The delta is the max distance between the values.

for the numbers, the characteristic value is

    
    
    [1.5, 6.5]
    

Because the values are grouped in [1,2] and [6,7] and calculated the average
value.


Answer: The problem description already gives it away: you want to use the `groupby()`
function from `itertools`

All that is needed is a slightly smarter `key` function, one that remembers
the last state and keeps on giving the same `key` value as long as successive
time stamps are closer closer than `delta`.

After grouping, transform the found groups to average times, taking care of
single time stamps (example included).

    
    
    import datetime as dt
    from itertools import groupby
    
    dates = [
            dt.datetime(1970, 1, 1, 0, 2),
            dt.datetime(1970, 1, 1, 0, 3),
            dt.datetime(1970, 1, 1, 0, 7),
            dt.datetime(1970, 1, 1, 0, 8),
            dt.datetime(1970, 1, 1, 0, 13)
        ]
    delta = dt.timedelta(minutes=2)
    
    class grouper:
        def __init__(self, delta):
            self.delta= delta
            self.last = None
    
        def __call__(self, tm):
            # we keep on returning the same key as long as successive time
            # stamps are within the last time stamp + delta
            self.last = tm if (self.last is None) or (tm - self.last)>self.delta \
                           else self.last
            return self.last
    
    # transform the result of groupby into average times
    def avgtm(item):
        (key, tms) = item
        tms = list(tms) # transform generator into list so we can index it
        return tms[0] + (tms[-1]-tms[0])/2 if len(tms)>1 else tms[0]
    
    timestamps = map(avgtm, groupby(dates, key=grouper(delta)))
    print "Time stamps: ",timestamps
    

Yields output:

    
    
    Time stamps:  [datetime.datetime(1970, 1, 1, 0, 2, 30), 
                   datetime.datetime(1970, 1, 1, 0, 7, 30),
                   datetime.datetime(1970, 1, 1, 0, 13)]
    

