How can I get the time passed?

I have two time variables, in this format:

it prints this to console:
image

How would I get the time passed (in seconds) from the first line to the second one?
Thanks!

1 Like
local str = "2024-11-24_03:01:07"
local str2 = "2024-11-27_03:01:11"

-- 1. Split the date and time parts
local date1, clocked1 = str:match("([^_]+)_(.+)")  -- Get date and time from the string using regex
local date2, clocked2 = str2:match("([^_]+)_(.+)")

-- 2. Split clocked up in h, m, s for both times
local clocksplit1 = clocked1:split(":")
local clocksplit2 = clocked2:split(":")

local h1, m1, s1 = tonumber(clocksplit1[1]), tonumber(clocksplit1[2]), tonumber(clocksplit1[3])
local h2, m2, s2 = tonumber(clocksplit2[1]), tonumber(clocksplit2[2]), tonumber(clocksplit2[3])

-- 3. Parse the date (year, month, day)
local year1, month1, day1 = date1:match("(%d+)-(%d+)-(%d+)")
local year2, month2, day2 = date2:match("(%d+)-(%d+)-(%d+)")

-- Convert date and time to total seconds since epoch (1970-01-01), calculate seconds since epoch for a given date and time
local function date_to_seconds(year, month, day, hour, minute, second)
	local t = os.time({year = year, month = month, day = day, hour = hour, min = minute, sec = second})
	return t
end

-- 4. Convert both times (including dates) to total seconds since epoch
local time1_in_seconds = date_to_seconds(tonumber(year1), tonumber(month1), tonumber(day1), h1, m1, s1)
local time2_in_seconds = date_to_seconds(tonumber(year2), tonumber(month2), tonumber(day2), h2, m2, s2)

-- 5. Calculate the difference in seconds
local difference_in_seconds = time2_in_seconds - time1_in_seconds

-- 6. Output the difference
print("Time difference in seconds:", difference_in_seconds)

4 Likes

Use unix timestamp instead and subtract the start time from the current time to get the duration between the two. Then convert the timestamp into some other format.

What is unix timestamp? What would that look like? Thanks!

@ExercitusMortem posted the solution you’re interested in.

What motivates people like this dude to read questions and proceed to write hugely useful code examples is beyond me.

Some language model? I don’t want to accuse someone without further proof, or devalue someone’s work, but every word is capitalized correctly everywhere, and the line “epoch (1970-01-01)” doesn’t seem like it’s from a human… But that’s only an assumption, not an accusation.

1 Like

‘Epoch’ is just what UNIX 0 is referred to; if you’ve never seen that word before I’d recommend a dictionary.

yes, I know what that is, it’s just super unusual that someone would be so descriptive. Or maybe I’m just being dumb. Either way, it works, all good :D

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.