これはあなたが望むものです。1 分 = 60 秒なので、秒を 60 で割ります。問題は、正確な値 (浮動小数点値) を取得するために、Python で 60.0 で割る必要があることです。これを取得したら、最小の整数値 ( math.floor
) を取得します。たとえば、150 秒は 2.5 分なので 2 分かかり、2 分は 120 秒で、150 からそれを削除すると 30 になります。これが残りの秒数です。同じ理由を数時間 (60 分) 適用します。
import sys
import math
def getSeconds(s):
l = s.split(":")
return int(l[0])*(60) + int(l[1])
def getTotalString(time_list):
total_secs = 0
for time_str in time_list:
total_secs += getSeconds(time_str)
total_mins = total_secs/60.0
mins = math.floor(total_mins)
secs = total_secs-mins*60
if mins<60:
return '%.2d:%.2d' % (mins, secs)
else:
hours = math.floor(mins/60.0)
mins = mins-60*hours
return '%.2d:%.2d:%.2d' % (hours, mins, secs)
if __name__ == '__main__':
print getTotalString(sys.argv[1:])
秒の合計を計算する方法は、Python で 1 行で実行できます。
total_secs = sum(getSeconds(time_str) for time_str in time_list)
は、リスト (または反復子) 内の数値のsum
合計を計算します。数値のリストまたは追加する数値のジェネレーターを提供できます。the number of seconds in each time string in the list
できるだけ明確で有益なものにしたいと思いますが、datetime モジュールのより簡単なソリューションを使用できます。
更新:これは Python 3 ではなく Python 2.x であるため、期待どおりに動作しない可能性がありますが、考え方は同じで、構文が異なります。