计算python中relativedelta的平均值

时间:2018-01-25 21:49:27

标签: python python-3.x python-datetime python-dateutil

我在Python 3中有多个relativedelta值,我想平均所有这些值。例如,对于下面的2个值,我想要relativedelta值,其中小时= + 3天(两者之间的平均值)。

relativedelta(days=+2, hours=+1, minutes=+33, seconds=+51)
relativedelta(hours=+4, minutes=+35, seconds=+36)

如何计算列表之间的平均值?如果有办法获得每个值的总小时数,我可以将它们相加并除以数值,然后除以24得到天数?

1 个答案:

答案 0 :(得分:0)

dateutil内无法直接执行此操作。您可以将两者锚定到datetime并在锚定日期之间找到timedelta。以下数字以天数表示,源于一天有86,400秒的事实:

from dateutil.relativedelta import relativedelta
from datetime import datetime      
from statistics import mean

def avg_relativedelta(*relativedeltas):
    dates = (anchor - rd for rd in relativedeltas)
    tds = (anchor - date for date in dates)
    return mean(td.total_seconds() for td in tds) / 86400

i1 = relativedelta(days=2, hours=1, minutes=33, seconds=51)
i2 = relativedelta(hours=4, minutes=35, seconds=36)
i3 = relativedelta(days=6, minutes=10)

avg_relativedelta(i1, i2, i3)
# 2.7545023148148147

avg_relativedelta(i1, i2)
# 1.12828125

您需要从relativedelta中减去datetime,然后从同一datetime中减去此datetime,这有点不直观。但基本上这是一种将relativedelta转换为timedelta的方法,后者可以汇总其单位。

可替换地:

def total_days_in_relativedelta(reldelta):
    total_days = reldelta.years * 365 \
               + reldelta.months * 12 \
               + reldelta.weeks * 52 \
               + reldelta.days \
               + reldelta.minutes * 1440 \
               + reldelta.seconds * 86400 \
               + reldelta.microseconds * 1000000
    return total_days


def avg_relativedelta(*relativedeltas):
    return mean(total_days_in_relativedelta(rd) for rd in relativedeltas)