Skip to content
AgileLogics
4 min read

Dates, Times, and the os Library

Prerequisites: Tables: the one data structure

Timestamps and formatting

local t = os.time({year = 2025, month = 4, day = 22, hour = 14, min = 30})
print(os.date("%Y-%m-%d %H:%M", t))
print(os.date("%A, %d %B %Y", t))

local d = os.date("*t", t)
print(d.year, d.month, d.day, d.wday, d.yday)

print(os.date("!%Y-%m-%d %H:%M:%S", 0))
2025-04-22 14:30
Tuesday, 22 April 2025
2025	4	22	3	112
1970-01-01 00:00:00
  • os.time(table) converts a date table (in local time) to a timestamp — seconds since 1970.
  • os.date(format, time) formats it with strftime codes; "*t" returns a table instead. A leading ! means UTC.
  • os.time() with no argument is now.

Date arithmetic

local start = os.time({year = 2025, month = 1, day = 10, hour = 12})
local finish = os.time({year = 2025, month = 1, day = 31, hour = 12})
print(os.difftime(finish, start) / 86400 .. " days")

local nextWeek = os.time({year = 2025, month = 1, day = 10 + 7, hour = 12})
print(os.date("%Y-%m-%d", nextWeek))

local normalized = os.time({year = 2025, month = 1, day = 35, hour = 12})
print(os.date("%Y-%m-%d", normalized))
21.0 days
2025-01-17
2025-02-04

os.time normalizes out-of-range fields — day 35 of January becomes February 4 — which makes "add N days" easy.

Timing code

local start = os.clock()
local sum = 0
for i = 1, 1e6 do sum = sum + i end
local elapsed = os.clock() - start
print(sum, elapsed >= 0)
500000500000	true

os.clock() measures CPU time, useful for benchmarking.

Other os functions

os.getenv("HOME") reads environment variables, os.execute(cmd) runs a shell command, os.exit(code) ends the program, and os.tmpname() returns a temporary file name. Many hosts remove os and io for security — see Sandboxing in Level 3.