The current time, durations, formatting and parsing dates, the monotonic clock, timers and tickers.
import time
The time package reads the clock, turns dates into text and back, does date arithmetic, measures how long code takes and waits. It works with two kinds of value:
•
An instant is an i64 count of seconds since the start of 1970 in UTC, the Unix epoch. Now returns one, and dates are stored, compared and sent as instants.
•
A duration is a Duration, a span with nanosecond precision such as 1h30m, which you can add up, compare and print.
There are also two clocks. The wall clock (Now, NowMillis) tells the date and can jump when the system time is set. The monotonic clock (MonoNanos) only moves forward and is the one to measure spans and deadlines with; timers and tickers use it.
For the Persian and Hijri calendars and for named time zones such as Asia/Tehran, see calendar. For timing parts of a program while you debug it, debug has named timers.
The things people get wrong:
•
Year, FormatDate, Format, FormatISO and Weekday use the machine's local time zone, so the same instant prints differently on a server set to UTC and a laptop in Tehran. Use the ...UTC functions and FormatISOUTC for anything stored or compared.
•
FormatISO has no offset, so the text cannot be read back to the same instant on another machine. Send FormatISOUTC or FormatRFC3339.
•
Days(30) is 30 times 24 hours, not a month. There is no month arithmetic; build the date with FromUTCParts and a month one higher (it rolls 13 over into January).
•
FromUTCParts and FromLocalParts accept any numbers and roll over: 30 February becomes 1 March. The parse functions, by contrast, throw for a day that the month does not have.
•
Timing code with Now. It has whole seconds and follows clock changes; use MonoNanos.
Dates from text, and date arithmetic
Dates usually arrive as text: from JSON, a database or a form. ParseISO reads the ISO 8601 form and returns the instant. Bad input is common, so it is declared throw: catch the error with try: ... catch e: and report or skip the value. Once you have an instant, arithmetic is plain integer arithmetic: AddDuration moves it, and DiffSeconds gives the distance between two instants.
time-guide-expiry.salam
import time
importstrfuncdays_left(expires: i64, today: i64): i64:
ret time.DiffSeconds(expires, today) / time.SecondsPerDay
endfuncmain:
today := time.FromUTCParts(2026, 3, 10, 9, 0, 0)
signups := [
"2026-01-15T08:30:00Z", "2026-02-20T18:45:00Z", "2026-03-09T23:10:00Z", "not a date"
]
each s in signups:
mut p := 0asi64try:
p = time.ParseISO(s)
catch e:
println"skipping \"" + s + "\":", e.message
continueend
expires := time.AddDuration(p, time.Days(30))
left := days_left(expires, today)
if left < 0:
println time.FormatISOUTC(p), "expired", -left, "days ago"else:
println time.FormatISOUTC(p),
"ends on",
time.FormatISOUTC(expires),
"(" + str.FromInt(left) + " days left)"endendend
Output
2026-01-15T08:30:00Z expired 24 days ago
2026-02-20T18:45:00Z ends on 2026-03-22T18:45:00Z (12 days left)
2026-03-09T23:10:00Z ends on 2026-04-08T23:10:00Z (29 days left)
skipping "not a date": expected a digit in the year, found 'n'
The example fixes "today" with FromUTCParts so its output never changes; a real program would use Now(). Adding Days(30) adds exactly 30 times 24 hours. In UTC that is always 30 calendar days, but in a zone with daylight saving the local clock time can move by an hour, so keep stored instants in UTC and convert only for display.
Timeouts from settings
A setting such as timeout = 1m30s is easier to read than a number of milliseconds. ParseDuration understands h, m, s, ms, us and ns, in any combination and with fractions. It throws on text it cannot read, and the error's message says why. Check the value against sensible limits too: a parse that worked is not yet a value that makes sense.
time-guide-timeouts.salam
import time
funcread_timeout(name: str, text: str, fallback: time.Duration): time.Duration:
mut d := fallback
try:
d = time.ParseDuration(text)
catch e:
println name + ": cannot read",
"\"" + text + "\" (" + e.message + "), using",
fallback.ToStr()
ret fallback
endif d.Less(time.Milliseconds(100)) or time.Minutes(10).Less(d):
println name + ":", d.ToStr(), "is out of range, using", fallback.ToStr()
ret fallback
endprintln name + ":", d.ToStr()
ret d
endfuncmain:
connect := read_timeout("connect", "2.5s", time.Seconds(5))
request := read_timeout("request", "1m30s", time.Seconds(30))
retry := read_timeout("retry", "soon", time.Seconds(1))
idle := read_timeout("idle", "2h", time.Minutes(5))
worst := connect.Add(request.Mul(3)).Add(retry.Mul(2))
println"worst case for three tries:", worst.ToStr()
println"idle in milliseconds:", idle.Millis()
end
Output
connect: 2.5s
request: 1m30s
retry: cannot read "soon" (expected a number, found 's'), using 1s
idle: 2h0m0s is out of range, using 5m0s
worst case for three tries: 4m34.5s
idle in milliseconds: 300000
Durations add, subtract, multiply and compare without any unit conversions, and to_str prints them in the same short form that ParseDuration reads. When a quick default is enough, ParseDurationOr does the parse and the fallback in one call.
When the text is not a date
ParseISO, ParseISONanos, ParseISOIn, ParseHTTPDate, ParseFormat and ParseDuration either return a value or throw an Error; nothing half-read comes back. e.kind tells the cases apart: Syntax for a character that does not fit, such as a slash where a dash belongs or a letter in the year, UnexpectedEnd for text that stops early, and OutOfRange for a field that is too large, such as month 13, hour 25, 30 February or a duration longer than about 292 years. e.offset and e.column point at the spot, and e.code is one of time.syntax, time.unexpected_end, time.empty, time.trailing, time.bad_month, time.bad_day, time.bad_hour, time.bad_minute, time.bad_second, time.bad_offset, time.bad_month_name, time.layout_mismatch, time.bad_unit, time.missing_unit or time.overflow. A layout that ParseFormat does not understand is the caller's mistake and throws InvalidArgument with time.bad_layout. When a default is fine, ParseISOOr and ParseDurationOr never throw; for the others, catch the error and use your default.
The next run of a daily job
An instant is seconds since 1970 in UTC, so the start of its UTC day is t - t % SecondsPerDay, and the time of day is the rest. That is enough to work out when a job that runs every night at 02:30 UTC should run next.
time-guide-schedule.salam
import time
funcweekday_name(epoch: i64): str:
names := ["Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"]
ret names[(epoch / time.SecondsPerDay) % 7]
endfuncnext_run(after: i64, hour: int, minute: int): i64:
day_start := after - after % time.SecondsPerDay
mut run := day_start + (hour asi64) * time.SecondsPerHour +
(minute asi64) * time.SecondsPerMinute
if run <= after:
run += time.SecondsPerDay
endret run
endfuncmain:
mut t := time.FromUTCParts(2026, 10, 16, 14, 20, 0)
println"now:", weekday_name(t), time.FormatISOUTC(t)
repeat3:
t = next_run(t, 2, 30)
println"backup:", weekday_name(t), time.FormatISOUTC(t)
endprintln"HTTP form:", time.FormatHTTPDate(t)
end
1 January 1970 was a Thursday, which is why the weekday table starts there. Weekday gives the same answer for the machine's local time. FormatHTTPDate is the form HTTP headers such as Last-Modified and Expires need.
Heartbeats, deadlines and waiting for a condition
A Ticker fires at a fixed interval: wait sleeps until the next tick, and if the program comes back late it skips the missed ticks instead of firing them all at once, counting them in dropped. A Timer is a single deadline you check with expired, here an upper limit for the whole loop. WaitUntil checks a condition every poll until it holds or limit runs out, which is the usual way to wait for a server or a file to appear.
time-guide-ticker.salam
import time
funcmain:
mut ticker := time.NewTicker(time.Milliseconds(20))
mut deadline := time.NewTimer(time.Milliseconds(500))
mut beats := 0until beats < 5andnot deadline.Expired():
ticker.Wait()
beats++
println"heartbeat", beats
end
ticker.Stop()
println"deadline passed:", deadline.Expired()
started := time.MonoNanos()
ready := time.WaitUntil((): ret time.SinceDuration(started).Millis() >= 30end, time.Milliseconds(5), time.Seconds(1))
println"cache warm:", ready
gave_up := time.WaitUntil((): retfalseend, time.Milliseconds(5), time.Milliseconds(20))
println"server came up:", gave_up
end
Output
heartbeat 1
heartbeat 2
heartbeat 3
heartbeat 4
heartbeat 5
deadline passed: false
cache warm: true
server came up: false
All of these run on the calling thread and block it. To do other work between ticks, call fired in your loop instead of wait; to run something truly in the background, start a thread.
Measuring how long code takes
Take MonoNanos before the work and pass it to SinceDuration after. The monotonic clock only moves forward, so the result is right even if the system clock is changed while the code runs; Now is for dates, not for timing.
time-guide-measure.salam
import time
funcfib(n: int): i64:
if n < 2:
ret n
endretfib(n - 1) + fib(n - 2)
endfuncmain:
start := time.MonoNanos()
result := fib(27)
took := time.SinceDuration(start)
println"fib(27) =", result
println"measured something:", not took.IsNegative()
println"under ten seconds:", took.Less(time.Seconds(10))
budget := time.Seconds(5)
if budget.Less(took):
println"slower than the budget of", budget.ToStr()
else:
println"within the budget of", budget.ToStr()
endend
Output
fib(27) = 196418
measured something: true
under ten seconds: true
within the budget of 5s
The example prints only comparisons, because the measured time is different on every run. To find the slow part of a larger program, the debug package has named timers that build on the same clock.
1710943509 2024-03-20T14:05:09Z
2024 3 20 14 5 9
Wed, 20 Mar 2024 14:05:09 GMT
true
true
true 1710943509250000000
2024-03-20T14:05:00Z
out of range time.bad_day 9 day 30 is out of range for month 2 of 2024 (1 to 29)
0
2024-03-30T14:05:09Z 864000 240h0m0s
60 3600 86400
Reads text such as 1h15m30.5s or -250ms. The units are ns, us, ms, s, m, h and d for days, and every number needs one. Throws Syntax for a character or unit it does not know, UnexpectedEnd for empty text or a number with no unit, and OutOfRange when the span does not fit in 64 bits of nanoseconds.
The monotonic clock in nanoseconds. It never goes backwards, even if the system clock is changed, so use it for measuring spans. Its value on its own means nothing as a date.
The example for this item is shown with the ones above: time-Now.salam
Waits for the given span and then runs the function. It happens on the same thread and does not return until the function is done, so it is a sleep followed by a call, not a background timer.
The example for this item is shown with the ones above: time-Timer.salam
Reads an ISO 8601 date and time, such as 2024-03-20T17:35:09+03:30 or 2024-03-20, and returns the instant in whole seconds; a fraction is checked and dropped. Without an offset it assumes local time. Throws Syntax or UnexpectedEnd for text in another shape and OutOfRange for a field that does not exist, such as month 13 or 30 February.
The example for this item is shown with the ones above: time-UTC.salam
Like ParseISO, but keeps the fraction of a second: it returns nanoseconds since the Unix epoch. Also throws OutOfRange for a date before 1677 or after 2262, which do not fit.
The example for this item is shown with the ones above: time-UTC.salam
Reads the date format of HTTP headers, such as Wed, 09 Jun 2021 10:18:14 GMT, and the two older forms HTTP still allows. The zone must be GMT, UTC or a numeric offset. Throws like ParseISO, and Syntax for an unknown month name.
The example for this item is shown with the ones above: time-UTC.salam
Reads text with a pattern. %Y is a four digit year, %y a two digit one, %m the month, %d the day, %H the hour, %M the minute, %S the second, %f the fraction, %b the English month name, %a the day name, which is ignored, %z an offset such as +0330 and %Z a zone name such as UTC. One space in the pattern matches any number of spaces in the text. Throws like ParseISO when the text does not fit the pattern, and InvalidArgument for a directive it does not know.
The example for this item is shown with the ones above: time-UTC.salam