Skip to content

Instantly share code, notes, and snippets.

@timendum
Created March 3, 2025 14:31
Show Gist options
  • Save timendum/9082903859931cf6618b58d28c2b5cba to your computer and use it in GitHub Desktop.
Save timendum/9082903859931cf6618b58d28c2b5cba to your computer and use it in GitHub Desktop.
Calc averange time
import math
PRECISION = 24 * 60
def average_time(times: list[str]) -> str:
sum_sin = 0.0
sum_cos = 0.0
for time_str in times:
hours, mins = map(int, time_str.split(':'))
total_mins = (hours % 24) * 60 + mins
angle = 2 * math.pi * total_mins / PRECISION
sum_sin += math.sin(angle)
sum_cos += math.cos(angle)
# Compute average angle
avg_angle = math.atan2(sum_sin, sum_cos)
# Convert back to minutes
avg_mins = round((avg_angle * PRECISION) / (2 * math.pi))
# Adjust for negative values
avg_mins = avg_mins % PRECISION
# Convert to hours and minutes
hours = int(avg_mins // 60)
minutes = int(avg_mins % 60)
return f"{hours:02d}:{minutes:02d}"
# Example usage:
print(average_time(["23:45", "00:17"]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment