[Django]-Get average of difference of datetime fields in django

4👍

You can combine aggregate, F expressions and Avg:

Doe.objects.all().aggregate(average_difference=Avg(F('end') - F('start')))

3👍

In addition to @ErwinJunge answer, to handle TypeError: float() argument must be a string or a number issue.

Create your own Avg class which will work with timedelta total seconds value:

from datetime import timedelta

class AvgTimeDelta(Avg):

    def convert_value(self, value, expression, connection, context):
        if value is None:
            return value
        if isinstance(value, timedelta):
            value = value.total_seconds()
        return float(value)

Then use it in the aggregate method:

average = Doe.objects.all().aggregate(
    average_difference=AvgTimeDelta(F('end') - F('start'))
)['average_difference']

And convert your average seconds amount back to timedelta:

average = timedelta(seconds=average)

Leave a comment