Average time for datetime list

前端 未结 4 2116
春和景丽
春和景丽 2020-12-10 05:13

Looking for fastest solution of time averaging problem.

I\'ve got a list of datetime objects. Need to find average value of time (excluding year, month, day). Here i

4条回答
  •  囚心锁ツ
    2020-12-10 05:24

    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)
    

提交回复
热议问题