Need to calculate total time month wise in django

I have created function to calculate total time.

def emp_attendance(request):
    attendance_list_ad = Attendance.objects.all()
    total = None
    for item in attendance_list_ad:
        if item.total_time is not None:
            if total is None:
                total = item.total_time
            else:
                total += item.total_time
    return render(request, 'employee/emp_attendance.html'{'attendance_list_ad': attendance_list_ad, 'total': 
                               total})

while print:

attendance date = 2023-01-09 total_time = 1: 00: 00

so my question is in front page this function is calculating total time of all enteries which are in data base . But i want to calculate total time month wise as in attendance date we have month 01 . then total time will be calculated

I am not sure I entirely understand your question.

Maybe the datetime module in Python will be helpful to you, maybe not.

Based on your comments on Trobosko's answer, it seems to me like you have a set of database entries and you need to filter out the results not regarding the current month. (followed by the actions you want to perform on the "clean" data, which you seem to have sorted out.)

That shouldn't be hard to do, I might be able to help if you provide some info on your database (maybe which one, the tables in question, and the query?). Perhaps also the format of the stored dates.

If you want to get sum of total time for each month you can do it like this...

from django.db.models import Sum
attendance_list_ad = Attendance.objects.filter(Date_field__year='2022').values_list('month').annotate(total_time=Sum('total_time'))

But if you are using dateTime field, and not just the month for each item. You could try doing the following, though I doubt it will work.

from django.db.models import Sum
attendance_list_ad = Attendance.objects.filter(Date_field__year='2022').values_list('Date_field__month').annotate(total_time=Sum('total_time'))
Back to Top