2024-04-24 23:10:51 发布
网友
从午夜开始换算成秒数和平均值有问题。如果你在23:50和00:10的时候这样做,你会在你想要的时候得到12:00。
更好的方法是average the angles。
import datetime import math import numpy def datetime_to_radians(x): # radians are calculated using a 24-hour circle, not 12-hour, starting at north and moving clockwise time_of_day = x.time() seconds_from_midnight = 3600 * time_of_day.hour + 60 * time_of_day.minute + time_of_day.second radians = float(seconds_from_midnight) / float(12 * 60 * 60) * 2.0 * math.pi return radians def average_angle(angles): # angles measured in radians x_sum = numpy.sum([math.sin(x) for x in angles]) y_sum = numpy.sum([math.cos(x) for x in angles]) x_mean = x_sum / float(len(angles)) y_mean = y_sum / float(len(angles)) return numpy.arctan2(x_mean, y_mean) def radians_to_time_of_day(x): # radians are measured clockwise from north and represent time in a 24-hour circle seconds_from_midnight = int(float(x) / (2.0 * math.pi) * 12.0 * 60.0 * 60.0) hour = seconds_from_midnight / 3600 minute = (seconds_from_midnight % 3600) / 60 second = seconds_from_midnight % 60 return datetime.time(hour, minute, second) def average_times_of_day(x): # input datetime.datetime array and output datetime.time value angles = [datetime_to_radians(y) for y in x] avg_angle = average_angle(angles) return radians_to_time_of_day(avg_angle) average_times_of_day([datetime.datetime(2017, 6, 9, 0, 10), datetime.datetime(2017, 6, 9, 0, 20)]) # datetime.time(0, 15) average_times_of_day([datetime.datetime(2017, 6, 9, 23, 50), datetime.datetime(2017, 6, 9, 0, 10)]) # datetime.time(0, 0)
下面是@eumiro对答案的一个可能实现,但是这个逻辑只有在这些是持续时间,而不是@lazyr指出的时间时才起作用:
from datetime import timedelta times = ['00:58:00','00:59:00','01:00:00','01:01:00','01:02:00'] print(str(timedelta(seconds=sum(map(lambda f: int(f[0])*3600 + int(f[1])*60 + int(f[2]), map(lambda f: f.split(':'), times)))/len(times))))
Also thanks to a post作者@silenghost,and a post作者@Herms
你不想以这种方式“平均”小时、分钟和秒的次数:
00:59:00 01:01:00
对01:00:00的平均值很清楚,但不符合您提出的逻辑。
01:00:00
相反,将所有时间间隔转换为秒,计算平均值并转换回HH:MM:SS。
HH:MM:SS
00:59:00 -> 3540 seconds 01:01:00 -> 3660 seconds ============ average: 3600 seconds converted to HH:MM:SS -> 01:00:00
从午夜开始换算成秒数和平均值有问题。如果你在23:50和00:10的时候这样做,你会在你想要的时候得到12:00。
更好的方法是average the angles。
下面是@eumiro对答案的一个可能实现,但是这个逻辑只有在这些是持续时间,而不是@lazyr指出的时间时才起作用:
Also thanks to a post作者@silenghost,and a post作者@Herms
你不想以这种方式“平均”小时、分钟和秒的次数:
对
01:00:00
的平均值很清楚,但不符合您提出的逻辑。相反,将所有时间间隔转换为秒,计算平均值并转换回
HH:MM:SS
。相关问题 更多 >
编程相关推荐