您至少可以使用sum()
生成器表达式来创建总秒数:
from datetime import datetime, date, time
def avg_time(datetimes):
total = sum(dt.hour * 3600 + dt.minute * 60 + dt.second for dt in datetimes)
avg = total / len(datetimes)
minutes, seconds = divmod(int(avg), 60)
hours, minutes = divmod(minutes, 60)
return datetime.combine(date(1900, 1, 1), time(hours, minutes, seconds))
演示:
>>> from datetime import datetime, date, time, timedelta
>>> def avg_time(datetimes):
... total = sum(dt.hour * 3600 + dt.minute * 60 + dt.second for dt in datetimes)
... avg = total / len(datetimes)
... minutes, seconds = divmod(int(avg), 60)
... hours, minutes = divmod(minutes, 60)
... return datetime.combine(date(1900, 1, 1), time(hours, minutes, seconds))
...
>>> avg_time([datetime.now(), datetime.now() - timedelta(hours=12)])
datetime.datetime(1900, 1, 1, 7, 13)