<p>如果您将HH:MM:SS改为秒(反之亦然)的代码改为其自身的函数,您将有一个更好的时间:</p>
<pre><code># Convert a h:m:s string to seconds
def hms_to_sec(hms):
h, m, s = [int(part, 10) for part in hms.split(":")]
return h * 60 * 60 + m * 60 + s
# Convert seconds to h:m:s
def sec_to_hms(s):
hm, s = divmod(s, 60)
h, m = divmod(hm, 60)
return "%02d:%02d:%02d" % (h, m, s)
# Source data (slightly modified from question so the guys have different times)
office_time_dict = {
"john": ["0:00:30", "0:02:04", "0:00:16"],
"bryan": ["0:00:20", "0:03:04", "0:00:16"],
"mike": ["0:00:10", "0:04:04", "0:00:16"],
}
# Convert each person's time to seconds and sum up
total_times_sec = {
person: sum(hms_to_sec(time) for time in times)
for (person, times) in office_time_dict.items()
}
# Convert the summed seconds back to H:M:S
total_times_hms = {
person: sec_to_hms(sec) for (person, sec) in total_times_sec.items()
}
# Sum the seconds and convert back to H:M:S
grand_total_hms = sec_to_hms(sum(total_times_sec.values()))
print(total_times_hms)
print(grand_total_hms)
</code></pre>
<p>这是打印出来的</p>
<pre><code>{'john': '00:02:50', 'bryan': '00:03:40', 'mike': '00:04:30'}
00:11:00
</code></pre>