Skip to content
Advertisement

Python Split and calculate

I use an API for the license overview, there I can see when and for how long I have used a program.

The usage time is displayed in a table as 10 min or as 1 h 10 min. Now I would like to have an printout under this table with the total used usage time.

for item in (data['data']):
    if item['un'] == tecNo:
        xyz= item['tu'].split(" ")
        print(xyz)

It Prints:

['20', 'min']
['35', 'min']
['1', 'h', '40', 'min']
['55', 'min']
['15', 'min']
['2', 'h']
['4', 'h', '25', 'min']
['15', 'min']
['30', 'min']
['45', 'min']
['1', 'h', '10', 'min']
['5', 'min']
['1', 'h', '10', 'min']
['35', 'min']
['55', 'min']
['1', 'h']
['1', 'h', '5', 'min']
['25', 'min']
['30', 'min']
['10', 'min']

How can I now calculate this so that I can print: "You have used X hours and Y minutes in total"?

Thank you very much!

The working Code

    total_hour = 0
    total_min = 0
    for item in (data['data']):
        if item['un'] == tecNo:
            xyz = item['tu'].split(" ")
            if xyz[1] == 'h':
                total_hour += int(xyz[0])
            if xyz[1] == 'min':
                total_min += int(xyz[0])
            if len(xyz) > 2:
                total_min += int(xyz[2])
    total_hour += (total_min // 60)
    total_min = (total_min % 60)
    print("You have used " +str(total_hour) + " h and " + str(total_min) + " m in total!")

Advertisement

Answer

total_hour = 0
total_min = 0
for item in (data['data']):
    if item['un'] == tecNo:
        xyz= item['tu'].split(" ")
        if xyz[1] == 'h':
            total_hour += xyz[0]
        if xyz[1] == 'min':
            total_min += xyz[0]
        if len(xyz)>2:
            total_min += xyz[2]
total_hour += (total_min//60)
total_min = (total_min%60)
print(total_hour+' h '+ total_min+ ' m')
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement