Search code examples
luaunix-timestamp

How to calculate the average of timestamps


I have a .log file that looks like this :

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

And what I need to do is to calculate the average on those timestamps, I wrote a function to calculate the average :

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

So basically what I'm doing is to sum the seconds, minutes, and hours and divide the results by the number of logs, for example if i have 10:15:46 and 10:09:33 i will add the seconds, minutes and hours and divide it by 2

is this the correct way to calculate the average of timestamps values?


Solution

  • I would be something like this solved the problem:

    --- 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) )