每次游完记一下次数。
from datetime import datetime def calculate_time(day_str, time_list): print("-" * 20) print(f"\033[34m{day_str}\033[0m 50米游泳记录") print("-" * 20) record = [] count_greater_than_70 = 0 count_less_than_65 = 0 count_between_65_and_70 = 0 for i in range(0, len(time_list) - 1): # 字符串的格式 format_string = "%M:%S" time1_str = time_list[i] time2_str = time_list[i + 1] # 将字符串转换为 datetime 对象 time1 = datetime.strptime(time1_str, format_string) time2 = datetime.strptime(time2_str, format_string) time_difference = time1 - time2 second = int(abs(time_difference.total_seconds())) if 60 < second < 100: record.append(second) if second > 70: count_greater_than_70 += 1 elif second < 65: count_less_than_65 += 1 else: count_between_65_and_70 += 1 print(f"{time1_str}-{time2_str} => {second}s") print("-" * 20) print(f"共 \033[34m{len(record)}次\033[0m,最快:\033[36m{min(record)}s\033[0m 最慢:\033[31m{max(record)}s\033[0m," f"其中 超过70s \033[31m{count_greater_than_70}次\033[0m,65~70s \033[33m{count_between_65_and_70}次\033[0m,低于65s \033[36m{count_less_than_65}次\033[0m") print("-" * 20) if __name__ == "__main__": D_2024_08_14 = ["15:52", "14:46", "13:55", "12:46", "12:36", "11:31", "08:20", "07:17", "07:15", "06:03", "05:58", "04:45", "04:42", "03:27", "03:35", "02:20", "02:12", "01:06", "01:02"] calculate_time("2024-08-14", D_2024_08_14)