简体   繁体   中英

Average difference between dates in Python

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?

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

Say a is your list

sumdeltas = timedelta(seconds=0)
i = 1
while i < len(a):
    sumdeltas += a[i-1] - a[i]
    i = i + 1

avg_delta = sumdeltas / (len(a) - 1)

This will indeed average your deltas together.

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM