如何从 csv 文件中的特定列读取十进制数将它们转换为 HH.MM 并计算总小时数

How to read decimal numbers from a specific column in a csv file convert them to HH.MM and total up the number of hours

我正在尝试创建一个程序来读取 csv 文件中具有十进制数字的第一行和第六行,然后将这些数字转换为 HH.MM。然后合计小时数并输出。

到目前为止,这是我的代码

import csv

with open("tracking_original2.csv") as f:
  reader = csv.reader(f, delimiter=',')
  rows = csv.reader(f)
  for row in rows:
    print(row[1],' ',row[6])

This outputs:
Customer   1
Customer   0.5
Customer   0.93
Customer   1.2
Customer   0.73
Customer   0.5
Customer   0.54
Customer   0.13
Customer   0.56
Customer   0.99

我完全不知道如何进行。有人可以帮忙吗?

你把你的小时数加起来,乘以 60 得到分钟数。然后提取完整的小时数和剩余的分钟数:

minutes = sum( [ 1 , 0.5 , 0.93 , 1.2 , 0.73 , 0.5 , 0.54 , 0.13 , 0.56 , 0.99 ]) * 60 
print( f'{int(minutes//60):02d}:{int(minutes)%60:02d}')

打印使用格式化得到00:00格式:见format mini languague and format string syntax

我正在使用整数除法 // 来获取完整的整数部分,并使用模数 % 来获取剩余的分钟数。我通过将结果转换为 int() 来丢弃任何小数部分 输出:

07:04

你也可以花点心思把它包装成一个函数:

def asHourString(decimalPlacesHours):
    """Converts decimal workhours into HH:MM format. 

    Works with int,float and list of float-convertables, else
    throws ValueError"""

    minutes = 0.0
    if isinstance(decimalPlacesHours,float) or isinstance(decimalPlacesHours,int) :
        minutes = decimalPlacesHours * 60
    elif isinstance(decimalPlacesHours,list) and decimalPlacesHours:
        try:
            minutes = sum(map(float,decimalPlacesHours))
        except (ValueError,IndexError):
            raise ValueError("Supply float or list convertable to float")
    else:   
        raise ValueError("Supply float or list convertable to float") 

    return f'{int(minutes//60):02d}:{int(minutes)%60:02d}'   

print(asHourString(21.49))
print(asHourString([21.49,2.12]))
print(asHourString(["21.49","2.12"])) 
print(asHourString(-5))
# print(asHourString("does not work")) # ValueError

输出:

21:29
00:23
00:23
-5:00