Average time for datetime list

Here’s a short and sweet solution (perhaps not the fastest though). It takes the difference between each date in the date list and some arbitrary reference date (returning a datetime.timedelta), and then sums these differences and averages them. Then it adds back in the original reference date.

import datetime
def avg(dates):
  any_reference_date = datetime.datetime(1900, 1, 1)
  return any_reference_date + sum([date - any_reference_date for date in dates], datetime.timedelta()) / len(dates)

Leave a Comment