Search code examples
pythondjangodatetimedjango-aggregationtimefield

convert double to time in python


I have a TimeField() in my django models. I want to convert the sum of the record of this to hours.

Here's the actual code in my view:

hours_week_decimal = Timesheet.objects.filter(owner = request.user.pk, week = datetime.datetime.now().isocalendar()[1]).aggregate(total=Sum('working_hour')) # this method return a dict of decimal
total_hours_week = convertDecimalToHours(hours_week_decimal)

and the related function:

def convertDecimalToHours(times):
    total_time = 0
    for k, v in times.items():
        total_time += int(v)
    print("type: {} - value: {}".format(type(total_time), total_time))

This returned me:

 type: int - value: 166000

I have two hours:

 Monday (08:30) and Tuesday(08:30)

It must have returned me "17:00"

Hope you can help me in solving this problem :)


Solution

  • The problem is that 30m+30m = 60m that yes, is 1h, but you expected that the calculator was able to understand that you want 30+30 = 1h So, in your case, you have to explicit convert 8:30 to 8.5

    A fast but not graceful approach to extend your example with few lines can be:

    • Convert your ints to strings.
    • Cut out the hours (positions 0 and 1) and multiply for 60 to obtain minutes.
    • Sum this result to the minutes (positions 2 and 3)

    After doing this for every TimeField you have, sum all your times converted in minutes and then reconvert in hours.

    In your example:

    def convertDecimalToHours(times):
    total_time = 0
    for k, v in times.items():
        tmp_time = str(int(v))
        minutes = int(tmp_time[2:4]) + int(tmp_time[0:2])*60
        total_time += minutes / 60 # Now your 8:30 is 8.5
    print("type: {} - value: {}".format(type(total_time), total_time))
    

    Your output here will be 17. I suggest you to use this as example to understand the concept, not as a packed solution to your problem.