python - 使用 python 从时间列表中创建平均值

标签 python

我有一个巨大的时间列表 (HH:MM:SS),我知道如果我想创建一个平均值,我可以将小时、秒和分钟分开并对每个时间进行平均,然后将它们连接起来。但是我觉得必须有更好的方法来做到这一点。有谁知道更好的方法吗?

谢谢!

最佳答案

转换为自午夜以来的秒数并求平均值时存在问题。如果你用 23:50 和 00:10 这样做,你会在你想要的 00:00 得到 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)

关于python - 使用 python 从时间列表中创建平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12033905/

相关文章:

python - 无法在 OpenCV(Python)中打开视频

python - 通过访问 token 连接到 Microsoft Graph

python - re.sub() 在多行之间替换

python - 检查是否定义了 sys.argv[x]

Python 3 FancyURLopener cookie 处理

python - 无法加载 native TensorFlow 运行时。运行 g2p-seq2seq --version 时

python - Socket.io 与 flask-socketio python。如何设置套接字保活/超时

java - Pyjnius 自定义 java 方法返回 'JavaException: Unable to find a None Method' 在 Public Static 之后工作

python - 在Python中使用for循环读取文件

Python 正则表达式 : find all lines that start with '{' and end with '}'