user10683480
user10683480

Reputation:

How to subtract two date and get the number of days in annotate?

I'm making a query to get the number of days from the date that a person bought a new phone until today.

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

When I retrieve the data, i got this 3150 days, 20:08:00 .

How can I do to remove the time because I just want to display the number of days?

I've tried:

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

the error returned: 'F' object has no attribute 'days'

I define todays_date like this todays_date = datetime.now().date(), the datebuy is DateTimeField

Upvotes: 3

Views: 1576

Answers (4)

Bharat Goel
Bharat Goel

Reputation: 1


from django.db.models.functions import Cast, ExtractDay, TruncDate

device_record = Devc.objects.annotate(
    duration = Cast(
        ExtractDay(
            TruncDate(todays_date) - TruncDate(F('datebuy'))
        ),
        IntegerField()
    ).order_by('datebuy')

Upvotes: 0

Sunil Jangid
Sunil Jangid

Reputation: 11

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

device_record = device_record.annotate(duration_in_days = F('duration__day'))

Upvotes: 1

Daedalus
Daedalus

Reputation: 416

You could try to subtract the timestamps and then retrieve the days.

from datetime import datetime, timedelta

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

print duration.days

Output:

1

Upvotes: 1

shafikshaon
shafikshaon

Reputation: 6404

If you need just a number of days a user buy a phone. You can query like this device_record = Devc.objects.order_by('datebuy')

Then in template {{ your_date_field|timesince:current_date_taht_can_be_return_from_view }}

Upvotes: 0

Related Questions