Averaging timestamp deltas with Django ORM

106 views
Skip to first unread message

Joshua Corlin

unread,
Sep 7, 2022, 7:22:23 PM9/7/22
to Django users
Hello Everyone, 

This is my first posting on this forum, please let me know if I have done anything incorrectly.  

I have a seemingly simple task I am trying to achieve with one of my projects.  Looking to see if the following is possible, and if so what the syntax would be with the Django ORM.  Apologies in advance if this is a trivial one. 

I have a requests model that has a bunch of time stamps(6 to be specific) and these timestamps record milestones in the request, set throughout the lifecycle of a request.  Im trying to write a query that gets a set of records, calculates the difference between two timestamps and averages those differences over the queryset.  For example, i want to get the average amount of time between the created_at timestamp and an approved_at timestamp over a set of records.  

I seem to be able to do this in postgres with the following, how can I do this with the Django ORM? 

select avg(approved_at - created_at) as approval_time from dashboard_labrequest;

Thanks in advance!

Thomas Lockhart

unread,
Sep 7, 2022, 7:47:18 PM9/7/22
to django...@googlegroups.com
Something like qs.aggregate(delay=Avg(F(“approved_at”) - F(“created_at”)))[“delay”]


hth

- Tom

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/da6f1f06-e036-46ce-9405-520004de18afn%40googlegroups.com.

Toshar Saini

unread,
Sep 8, 2022, 12:47:25 PM9/8/22
to django...@googlegroups.com
Something like qs.aggregate(delay=Avg(F(“approved_at”) - F(“created_at”)))[“delay”]
try this

Joshua Corlin

unread,
Sep 15, 2022, 9:19:57 AM9/15/22
to Django users

Thank you, this is exactly what I was looking for

-Josh

subin

unread,
Sep 16, 2022, 1:45:28 PM9/16/22
to django...@googlegroups.com
Reply all
Reply to author
Forward
0 new messages