如何计算时间戳的平均值

我有一个.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) --将值转换为数字
        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:46”和“10:09:33”,我将把秒、分钟和小时相加,然后除以2

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

点赞
用户7504558
用户7504558
--- 例子 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) )

我会做得像这样解决这个问题:

2019-12-20 12:17:50