Using python to create an average out of a list of times

python average of list
how to find the average of 3 numbers in python
program to find average of n numbers in python
average of list of numbers
how to find average in dictionary python
python average of list using for loop
python calculate average from file
average all items in list python

I have a huge list of times (HH:MM:SS) and I know that if I wanted to create an average I could separate the Hours, Seconds, and Minutes and average each one and then concatenate them back together. However I feel that there must be a better way to do that. Does anyone know of a better way to do this?

Thanks!

You don't want to "average" times on hours, minutes and seconds this way:

00:59:00
01:01:00

average clearly to 01:00:00, but not with the logic you presented.

Instead convert all your time intervals into seconds, calculate the average and convert back to HH:MM:SS.

00:59:00 -> 3540 seconds
01:01:00 -> 3660 seconds
            ============
average:    3600 seconds converted to HH:MM:SS -> 01:00:00

Find AVERAGE of a List in Python with Example, Python Average via Loop; Using sum() and len() built-in functions; Using mean function from statistics module; Using mean() from numpy library  Find learn python programming on KensaQ.com. KensaQ updates its results daily to help you find what you are looking for. Search Now!

Here is one possible implementation of the answer by @eumiro, but this logic only works if these are durations, not times, as pointed out by @lazyr:

from datetime import timedelta

times = ['00:58:00','00:59:00','01:00:00','01:01:00','01:02:00']

print(str(timedelta(seconds=sum(map(lambda f: int(f[0])*3600 + int(f[1])*60 + int(f[2]), map(lambda f: f.split(':'), times)))/len(times))))

Also thanks to a post by @SilentGhost, and a post by @Herms

Find average of a list in python, Check out this Author's contributed articles. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org​  Find learn to use python on TheAnswerHub.com. TheAnswerHub is a top destination for finding answers online. Browse our content today!

There's a problem with converting to seconds since midnight and averaging. If you do that with 23:50 and 00:10 you get 12:00 when what you want it 00:00.

A better approach is to average the angles.

import datetime
import math
import numpy

def datetime_to_radians(x):
    # radians are calculated using a 24-hour circle, not 12-hour, starting at north and moving clockwise
    time_of_day = x.time()
    seconds_from_midnight = 3600 * time_of_day.hour + 60 * time_of_day.minute + time_of_day.second
    radians = float(seconds_from_midnight) / float(12 * 60 * 60) * 2.0 * math.pi
    return radians

def average_angle(angles):
    # angles measured in radians
    x_sum = numpy.sum([math.sin(x) for x in angles])
    y_sum = numpy.sum([math.cos(x) for x in angles])
    x_mean = x_sum / float(len(angles))
    y_mean = y_sum / float(len(angles))
    return numpy.arctan2(x_mean, y_mean)

def radians_to_time_of_day(x):
    # radians are measured clockwise from north and represent time in a 24-hour circle
    seconds_from_midnight = int(float(x) / (2.0 * math.pi) * 12.0 * 60.0 * 60.0)
    hour = seconds_from_midnight / 3600
    minute = (seconds_from_midnight % 3600) / 60
    second = seconds_from_midnight % 60
    return datetime.time(hour, minute, second)

def average_times_of_day(x):
    # input datetime.datetime array and output datetime.time value
    angles = [datetime_to_radians(y) for y in x]
    avg_angle = average_angle(angles)
    return radians_to_time_of_day(avg_angle)

average_times_of_day([datetime.datetime(2017, 6, 9, 0, 10), datetime.datetime(2017, 6, 9, 0, 20)])
# datetime.time(0, 15)

average_times_of_day([datetime.datetime(2017, 6, 9, 23, 50), datetime.datetime(2017, 6, 9, 0, 10)])
# datetime.time(0, 0)

Python statistics, Pseudo-polynomial Algorithms · Polynomial Time Approximation Scheme mean() function can be used to calculate mean/average of a given list of numbers​. It is a measure of the central location of data in a set of values which vary in range. from statistics import mean Check out this Author's contributed articles​. First parse the time from string format to time struct using strptime, then convert the time to seconds from epoch using mktime, then you should add all the seconds and divide by the number of times, and to convert back to time struct using localtime

You need to convert it to complex numbers, take the argument and then average the degrees.

Finally you'll need to parse date to get what you want and then convert back to the original hour.

from cmath import rect, phase
from math import radians, degrees

def meanAngle(deg):
    complexDegree = sum(rect(1, radians(d)) for d in deg) / len(deg)
    argument = phase(complexDegree)
    meanAngle = degrees(argument)
    return meanAngle

def meanTime(times):
    t = (time.split(':') for time in times)
    seconds = ((float(s) + int(m) * 60 + int(h) * 3600) 
               for h, m, s in t)
    day = 24 * 60 * 60
    toAngles = [s * 360. / day for s in seconds]
    meanAsAngle = meanAngle(toAngles)
    meanSeconds = meanAsAngle * day / 360.
    if meanSeconds < 0:
        meanSeconds += day
    h, m = divmod(meanSeconds, 3600)
    m, s = divmod(m, 60)
    return('%02i:%02i:%02i' % (h, m, s))

print(meanTime(["15:00:00", "21:00:00"]))
# 18:00:00
print(meanTime(["23:00:00", "01:00:00"]))
# 00:00:00

Python Program to Calculate the Average of Numbers in a Given List , Python Program to Calculate the Average of Numbers in a Given List from 0 to the number of elements and is incremented each time after the body of the To practice all Python programs, here is complete set of 150+ Python Problems and​  C:\pythontest>python testavg.py The average is 31.86 Summary: The formula to calculate average is done by calculating the sum of the numbers in the list divided by the count of numbers in the list. The average of a list can be done in many ways i.e . Python Average by using the loop; By using sum() and len() built-in functions from python

First parse the time from string format to time struct using strptime, then convert the time to seconds from epoch using mktime, then you should add all the seconds and divide by the number of times, and to convert back to time struct using localtime

Here is an example:

import time


a = time.strptime("2000:11:12:13","%Y:%H:%M:%S")
b = time.strptime("2000:11:14:13","%Y:%H:%M:%S")

avg_time = time.localtime(((time.mktime(a)+time.mktime(b))/2))

>> time.struct_time(tm_year=2000, tm_mon=1, tm_mday=1, tm_hour=11, tm_min=13, tm_sec=13, tm_wday=5, tm_yday=1, tm_isdst=0)

Note that I added the year 2000 because mktime is giving OverflowError for the default year 1900

How to take the average of a list in Python, Let's have a look at a few of the algorithms used to compute the average for a list of numbers. 1. Using sum() and len()  That’s the beauty of python. The final average value is calculated by dividing the total sum by the total number of elements in the list. ‘sum’ method is used to find out the sum of all numbers in the list and len () method is used to find out the length of the list. 2.

Python Exercise: Calculate the sum and average of n integer , Next: Write a Python program to create the multiplication table (from 1 to 10) of a number. What is the difficulty level of this exercise? Easy Medium Using sum () In Python we can find the average of a list by simply using the sum () and len () function. sum () : Using sum () function we can get the sum of the list. len () : len () function is used to get the length or the number of elements in a list. filter_none.

Loops and lists, Loops are used to repeat a collection of program statements several times. A list element can be any Python object, including numbers, strings, functions, and Compute the average number of sun hours for each month during the total data data from the Oxford_sun_hours.txt file into the program file and set a variable​  The function itertools.repeat doesn't actually create the list, it just creates an object that can be used to create a list if you wish! Let's try that again, but converting to a list: >>> timeit.timeit('list(itertools.repeat(0, 10))', 'import itertools', number = 1000000) 1.7508119747063233 So if you want a list, use [e] * n.

Basic Statistics, Further revisions may include the geometric and harmonic mean. filter, creating a series of averages using a user-defined number of subsets of the full data set. + 1/2*e sage: median(['sage', 'linux', 'python']) 'python' sage: median([]) NaN sage: occurs in v, then the mode is the list of elements of v that occur n times. Calculate the sum and average of a given list in Python Let see you have a list of numbers and you want to calculate the sum of numbers present in the list. All you need to do is to iterate a list using a for loop and add each number to a sum variable. To calculate the average divide the sum by the length of a given list(total numbers in a list)

Comments
  • Give a (short) example of input and output in proper Python.
  • how about just taking an absolute time total # seconds = hours * 3600 + minutes * 60 + seconds and averaging that and putting it back together as a time?
  • Could you provide some sample data please. Do you have the data in strings, timedelta, etc. ...
  • Beware that if what you're averaging is not duration but points in time, then it wraps around and the average becomes a wooly concept -- you need to define what happens around midnight. For example, what is the average of 23:59:58 and 00:00:00? Is it 23:59:59 or 11:59:59?
  • I think this one should have been the accepted answer. It worked perfectly for me. Anyhow, there's one little detail to adjust: the line hour = seconds_from_midnight / 3600 should be modified to hour = (seconds_from_midnight / 3600) % 24 to handle cases in which hour has a negative value. The error can be reproduced by computing the mean of, for instance, 18:20 and 20:35
  • I think it should be radians = float(seconds_from_midnight) / float(24 * 60 * 60) * 2.0 * math.pi and seconds_from_midnight = int(float(x) / (2.0 * math.pi) * 24.0 * 60.0 * 60.0) note 24 instead of 12 - to make 24 hours = 2pi (360 degrees). And the above comment is still valid.