如何计算时间戳的平均值

问题描述 投票:0回答:1

我有一个.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

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

lua unix-timestamp
1个回答
0
投票

我会这样解决问题:

--- 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) )
© www.soinside.com 2019 - 2024. All rights reserved.