views:

926

answers:

5

I have a series of datetime objects and would like to calculate the average delta between them.

For example, if the input was (2008-10-01 12:15:00, 2008-10-01 12:25:00, 2008-10-01 12:35:00), then the average delta would be exactly 00:10:00, or 10 minutes.

Any suggestions on how to calculate this using Python?

+7  A: 

As far as algorithms go, that's an easy one. Just find the max and min datetimes, take the difference, and divide by the number of datetimes you looked at.

If you have an array a of datetimes, you can do:

mx = max(a)
mn = min(a)
avg = (mx-mn)/(len(a)-1)

to get back the average difference.

EDIT: fixed the off-by-one error

Randy
Shouldn't it be (len(c) - 1)?
Patrick McElhaney
Yes indeed. Thanks, Patrick.
Randy
Shouldn't it be (len(a) - 1)? - since the other references seems to be to 'a' and not 'c'...
Jonathan Leffler
Yeah, that would be good too.
Randy
Can you divide timedelta objects?
Eugene
Yep, it appears to be doing fine with the division here.
Randy
+1  A: 

Since you seem to be throwing out the 20 minute delta between times 1 and 3 in your example, I'd say you should just sort the list of datetimes, add up the deltas between adjacent times, then divide by n-1.

Do you have any code you can share with us, so we can help you debug it?

Bill the Lizard
A: 

You can subtract each successive date from the one prior (resulting in a timedelta object which represents the difference in days, seconds). You can then average the timedelta objects to find your answer.

Ben Hoffstein
Yep, that's what I'm trying to do. The averaging seems to be causing an issue; probably a Python mistake on my part. Ideas?
Eugene
Please post your code.
S.Lott
A: 

Say a is your list.

numdeltas = len(a) - 1
sumdeltas = 0
i = 1
while i < len(a):
    sumdeltas += a[i] - a[i-1]
avg = sumdeltas / numdeltas

This will indeed average your deltas together.

Claudiu
A: 

small clarification

from datetime import timedelta

def avg(a):
    numdeltas = len(a) - 1
    sumdeltas = timedelta(seconds=0)

    i = 1
    while i < len(a):
        delta = abs(a[i] - a[i-1])
        try:
            sumdeltas += delta
        except:
            raise
        i += 1
    avg = sumdeltas / numdeltas
    return avg
sergey