首页 > 解决方案 > 如何减去两个日期并获得注释中的天数?

问题描述

我正在查询从一个人购买新手机之日到今天的天数。

device_record = Devc.objects.annotate(duration = todays_date - F('datebuy'))\
    .order_by('datebuy')

当我检索数据时,我得到了这个3150 days, 20:08:00

我该怎么做才能删除时间,因为我只想显示number of days

我试过了:

device_record = Devc.objects.annotate(duration = (todays_date - F('datebuy')).days)\
        .order_by('datebuy')

返回的错误: 'F' object has no attribute 'days'

我这样定义 todays_date todays_date = datetime.now().date()datebuyDateTimeField

标签: djangodjango-views

解决方案


您可以尝试减去时间戳,然后检索日期。

from datetime import datetime, timedelta

now = datetime.now()
yesterday =  now - timedelta(days=1)
duration = now - yesterday

print duration.days

输出:

1


推荐阅读