【问题标题】:How to calculate exact age from database birthday field and date.today()?如何从数据库生日字段和 date.today() 计算确切年龄?
【发布时间】:2019-08-05 18:30:33
【问题描述】:

我有两个约会:

  1. 来自数据库的查询集,其中包括日期字段 (1992-11-15) 和 date.today()

这是我的意见.py

    def pop(request):
    start = randint(0, 2)
    finish = randint(2, 5)
    current_year = [date.today().year, date.today().year]
    context = {
        'alluserprofiles': zip(Profile.objects.all()[start:finish], 
    current_year),
        'maleuserprofiles': zip(Profile.objects.filter(gender='male'), current_year),
        'femaleuserprofiles': zip(Profile.objects.filter(gender='female'), current_year),
        'start': start,
        'finish': finish
    }
    return render(request, 'users/pop.html', context)

这是我的 django 模板

   {% for profile, year in alluserprofiles %}
<div class="container fixed-top" id="pop-up">
  <div class="card text-center border-light mb-3">
    <img class="card-img-top" src="{{ profile.image_prof.url }}" />
    <div class="card-body">
            <h5> {{ profile.user }} {{ year|sub:profile.birthday.year}}

如何减去它们以获得确切的年龄?我只能管理年份减法。

非常感谢

【问题讨论】:

标签: python django


【解决方案1】:

复制于:Subtracting Dates With Python

from datetime import datetime

birthday = datetime(1988, 2, 19, 12, 0, 0)
diff = datetime.now() - birthday
print diff
# 8954 days, 7:03:45.765329

(对不起,我只能回答,因为我没有足够的声誉)

【讨论】:

    【解决方案2】:

    如下所示,

    import datetime
    
    def age_calc(dob):
       return date.today().year - dob.year - ((date.today().month, date.today().day) < (dob.month, dob.day))
    

    【讨论】:

      【解决方案3】:

      解决办法

      {{ profile.birthday|timesince:year|slice:":2" }}
      

      最后切片得到年龄数字

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-22
        • 2023-03-14
        • 1970-01-01
        • 2013-10-31
        • 1970-01-01
        • 1970-01-01
        • 2012-02-06
        • 2018-07-23
        相关资源
        最近更新 更多