用Python计算平均年龄

时间:2011-12-27 12:58:23

标签: python django

我正在使用Django并试图计算客户的平均年龄,由于某种原因,这个答案正在逃避我。我想要做的是遍历一个组中的所有客户端,并获得今天及其dob的平均增量。

这是模型的样子:

class Client (models.model):
  ...
  dob = models.DateField(
                         null = False
                        )

所以我试图做这样的事情:

def age(self,qrydtm=date.today())
  # here is a method (from funcs.py) that returns a list of dob for the group
  delta = 
  delta_m = ((qrydate.year - self.dob.year)*12)+(qrydate.month - self.dob.month)         
  years = delta_m // 12
  weeks = delta // 7
  months = (delta_m - (years*12))
  if (years > 0):
    return ('%s yr - %s mn' % (years,months))
  else:
    return ('%s wk' % (weeks))  

我正在使用的方法,创建一个像这样的dob列表[(datetime.date(1976,8,4),),(datetime.date(2005,8,8),),(datetime.date( 1986,10,14),)]

2 个答案:

答案 0 :(得分:1)

这将为您提供平均年龄作为timedelta:

l = [datetime.date(1976, 8, 4), datetime.date(2005, 8, 8), ...] # values_list(flat=True)
today = datetime.date.today()
average_age = sum(map(lambda x: today-x, l), datetime.timedelta(0))/len(l)

修改

由于l有效,我避开了第二个清单:

from datetime import date, timedelta
l = [date(1976, 8, 4), date(2005, 8, 8), ...] # values_list(flat=True)
today = date.today()
average_age = sum((today - x for x in l), timedelta(0)) / len(l)

答案 1 :(得分:0)

以下是使用relativedelta的已接受答案的改编解决方案,该解决方案更具描述性:

from datetime import date
from dateutil.relativedelta import relativedelta
l = [date(2006, 9, 17), date(2004, 9, 17), ]
today = date.today()
average_age = sum((relativedelta(today, x) for x in l), relativedelta(0)) / len(l)

然后average_age输出relativedelta(years=+11, months=+4, days=+17)