如何计算时间戳的平均值

How to calculate the average of timestamps

我有一个如下所示的 .log 文件:

--hh:mm:ss
10:15:46
10:09:33
10:27:26
10:09:49
09:54:21
10:10:25

我需要做的是计算这些时间戳的平均值,我写了一个函数来计算平均值:

function calculate_average_working_hours(working_day_diff)

local current_hour, current_minutes, current_secondes = 0, 0, 0
    local total_hour, total_minutes, total_secondes = 0, 0, 0
    local working_days_counter = #working_day_diff

    for key, value in pairs(working_day_diff) do
        current_hour, current_minutes, current_secondes = extract_timestamp_value(value) --covert the values to numbers
        total_hour = total_hour + current_hour
        total_minutes = total_minutes + current_minutes
        total_secondes = total_secondes + current_secondes
    end

    total_hour = math.ceil(total_hour / working_days_counter)
    total_minutes = math.ceil(total_minutes / working_days_counter)
    total_secondes = math.ceil(total_secondes / working_days_counter)

    return ("%02d:%02d"):format(total_hour, total_minutes)
end

所以基本上我所做的是将秒、分钟和小时相加,然后将结果除以日志数, 例如,如果我有 10:15:4610:09:33,我将添加秒、分钟和小时并将其除以 2

这是计算时间戳值平均值的正确方法吗?

我会像这样解决问题:

--- example 1
local log = [[--hh:mm:ss
10:15:46
10:09:33
10:27:26
10:09:49
09:54:21
10:10:25
]]

local function seconds(v) 
    local h,m,s = v:match("(%d%d):(%d%d):(%d%d)") 
    if h and m and s then return h*3600+m*60+s else return nil end 
end
local i,sum = 0, 0
for line in log:gmatch('(.-)[\r\n]') do    
    local r = seconds(line)
    if r then i=i+1; sum = sum+r end
end
print(sum,i, os.date("!%X",sum/i) )