Skip to content
Tutorials Center
My learning

Topics

Lesson 86 of 132 ยท Standard Library Tour

Time, Duration and Instant

Work with time in Rust: Duration arithmetic, measuring with Instant, SystemTime and UNIX_EPOCH, formatting durations and dates by hand, sleeping, and testable clocks.

Almost every real program touches time. It measures how long something took, waits before retrying, stamps a log line, or checks whether a token has expired. The Rust standard library covers these jobs with three small types in std::time: Duration (a span of time), Instant (a point on a steady clock, for measuring) and SystemTime (a point on the wall clock, for dates). They look similar, but they exist for different reasons, and using the wrong one is the classic source of time bugs.

What the standard library deliberately leaves out is the calendar: months, time zones, daylight saving time, parsing and formatting dates. That job belongs to crates such as chrono, time and jiff. In this lesson you will learn the three std types, do Duration arithmetic safely, measure code correctly, convert a Unix timestamp to a calendar date by hand (so you see what those crates do for you), and structure code so that tests do not need real clocks.

Time-dependent output is never the same twice. In this lesson, runnable examples print only values that are always the same: fixed durations, computed dates, and true/false answers such as "did the sleep last at least 20 ms?". We never print the current time or a measured elapsed time. In your own programs, printing them is fine.

Duration: a span of time

A Duration is a number of seconds plus a number of nanoseconds. It is never negative, it is Copy, and it is stored as a u64 of seconds and a u32 of nanoseconds, so it can represent more than 500 billion years with nanosecond precision.

Rust Creating and inspecting durations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Two details trip people up. First, as_secs() returns only whole seconds and throws the rest away: Duration::from_millis(1_500).as_secs() is 1, not 1.5. Use as_secs_f64() for a fractional value, or as_millis() for a total in milliseconds. Second, subsec_millis() is only the part after the whole seconds, so it is 500 here, not 1500.

Duration arithmetic

You can add durations, subtract them, multiply and divide them by integers, and compare them. Each of these operations has a checked form, because durations are unsigned and can overflow.

Rust Arithmetic, checked and saturating

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Duration::from_mins and from_hours were added in Rust 1.91, abs_diff in 1.81 and div_duration_f64 in 1.80. Earlier code multiplies by 60 or 3,600 by hand.

What happens if you ignore the unsigned nature? A plain - operator panics when the result would be negative:

Rust Subtracting too much (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The program stops with thread 'main' panicked at ...: followed by overflow when subtracting durations, and exit code 101. This is a real bug source: "time remaining" computations often go negative when a deadline has just passed. Use checked_sub and decide what "already late" means, or saturating_sub when zero is a sensible answer.

Instant: measuring elapsed time

Instant is a reading of a monotonic clock: one that only moves forward and is never adjusted when someone changes the system date or the network syncs the clock. That is exactly what you want for measuring how long something took. An Instant has no meaning on its own (you cannot turn it into a date, and printing it shows an opaque value). Its only use is to compare it with another Instant.

Rust
use std::time::Instant;

let start = Instant::now();
do_work();
let took = start.elapsed();              // a Duration
println!("work took {took:?}");
Rust Measuring with Instant (without printing times)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Some notes for good measurements:

  • Always measure around the work only. Compute elapsed() immediately after the work, not after printing.
  • One measurement is noise. The first run is slow (cold caches, page faults), the next may be interrupted by another process. For serious benchmarks use many iterations and a harness such as Criterion, and make sure the optimizer cannot delete the code you measure (std::hint::black_box, see performance).
  • Debug builds are slow. Measure with cargo run --release.
  • Resolution differs by platform. Do not rely on nanosecond precision.

SystemTime and the Unix epoch

SystemTime is the wall clock: the date and time the computer believes it is. Unlike Instant, it can jump backwards or forwards (the user changes the clock, NTP corrects it), so it is a poor choice for measuring durations but the right one for timestamps that are stored or shown to people.

The usual way to get a number out of it is to measure the distance from UNIX_EPOCH, midnight UTC on 1 January 1970. That distance is the famous Unix timestamp. Because the system clock might be set before 1970, duration_since returns a Result.

Rust SystemTime and UNIX_EPOCH

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Notice the error type: SystemTimeError carries the difference, available through .duration(). The last line shows that on most platforms you can represent times before 1970 too; the Result is there because the clock is not guaranteed to be sane.

Rule of thumb: Instant for measuring, SystemTime for dates

Question Use
How long did this take? Has the timeout passed? Instant and Duration
When did this happen? (store in a file or database) SystemTime (or a crate type)
Compare timestamps from different machines SystemTime, with clock skew in mind
Sleep for 5 seconds thread::sleep(Duration)

Turning a timestamp into a calendar date

The standard library cannot tell you "this is 14 November 2023". To understand what date libraries do, here is the conversion by hand, using the well-known civil from days algorithm: split the timestamp into days and seconds, then convert a day count since 1970 into year, month and day with integer arithmetic. UTC only, no time zones.

Rust From Unix timestamp to calendar date

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Look at the last timestamps: -86_400 correctly becomes 31 December 1969, thanks to div_euclid and rem_euclid, which round toward negative infinity instead of toward zero. Everything else in a date library (time zones with daylight saving rules, locale names, parsing "2024-03-09T10:00:00+02:00", month arithmetic) is a lot more work than this, which is the reason to use a crate for anything user-facing.

Calendar crates (read-only)

The three popular choices are chrono, time and jiff. Each needs Cargo.toml entries, so these snippets cannot run in our editor.

TOML
# Cargo.toml (read-only: needs Cargo and crates.io)
[dependencies]
chrono = "0.4"
Rust
// read-only: needs the chrono crate
use chrono::{DateTime, Duration, Utc};

fn main() {
    let now: DateTime<Utc> = Utc::now();
    println!("{}", now.format("%Y-%m-%d %H:%M:%S"));

    let next_week = now + Duration::days(7);
    println!("{}", next_week.to_rfc3339());
}
  • chrono is the long-established library; it has time zones through chrono-tz, and a huge ecosystem.
  • time is leaner and has a macro for compile-time checked dates (datetime!(2024-03-09 10:00 UTC)).
  • jiff is newer and designed around time zones as a first-class feature, with daylight-saving-aware arithmetic.

Whichever you choose, store timestamps in UTC and convert to a local time zone only when displaying them.

Formatting durations for people

The Debug output of a Duration is handy for logs (1.5s, 42ยตs) and accepts a precision: {:.2?} gives 1.50s. For user-facing text you will usually want your own format, like 1h 02m 03s.

Rust Human-friendly duration formatting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Sleeping, timeouts and deadlines

thread::sleep(duration) pauses the current thread for at least that long. Many standard library calls accept a timeout too: Receiver::recv_timeout, Condvar::wait_timeout, TcpStream::set_read_timeout, thread::park_timeout. The usual way to implement "retry for up to N seconds" is to compute a deadline once and compare against it, instead of adding up sleeps (which drift).

Rust Timeouts and a deadline loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Make time testable with a clock trait

Code that calls Instant::now() or SystemTime::now() directly is hard to test: the test would have to sleep for real, and the result changes from run to run. A common remedy is to pass time in through a small trait. Production code uses the real clock; tests use a fake clock that you advance by hand.

Rust A Clock trait with a fake clock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The test runs instantly and always gives the same answer, even though the token "lives" for an hour. See testing in Rust for how to turn this into #[test] functions.

Common mistakes

  • Using SystemTime to measure elapsed time. If the clock is adjusted during the measurement, you get a wrong or negative result. Use Instant.
  • Storing Instant. It cannot be saved to a file or sent to another machine. Store a SystemTime, a Unix timestamp or a formatted UTC string.
  • Truncating with as_secs(). Duration::from_millis(999).as_secs() is 0.
  • Plain - on durations or instants. It can panic. Use checked_sub or saturating_duration_since.
  • Assuming sleep is exact. It is a lower bound.
  • Doing calendar math by hand. "Add one month" or "next midnight in Berlin" depends on rules that change. Use a crate.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which type should you use to measure how long a function took?

    Instant never goes backwards and ignores clock changes, so elapsed() is reliable. SystemTime can jump when the system clock is adjusted.
  2. 2. What does Duration::from_millis(1_500).as_secs() return?

    as_secs returns whole seconds only and drops the fraction. Use as_secs_f64 or as_millis for more precision.
  3. 3. What happens with Duration::from_secs(1) - Duration::from_secs(2)?

    Durations are unsigned, so the plain minus operator panics when the result would be negative. Use checked_sub (an Option) or saturating_sub (zero) to handle it.
  4. 4. Why does SystemTime::duration_since return a Result?

    A Duration cannot be negative. If the argument is later than self, you get a SystemTimeError that tells you how far apart the two times are.
  5. 5. What is the main reason to pass a Clock trait object or generic into code that depends on time?

    With a fake clock you can advance time by hand, so a test about a one-hour expiry does not need to wait an hour.

Summary

  • Duration is an unsigned span (seconds plus nanoseconds). Use as_secs_f64, as_millis and friends carefully, and prefer checked_sub or saturating_sub over -.
  • Instant is a monotonic clock for measuring; it has no calendar meaning, so never print or store it. Time only the work, repeat measurements, and use release builds.
  • SystemTime is the wall clock. duration_since(UNIX_EPOCH) gives a Unix timestamp and returns a Result because clocks can be wrong.
  • The standard library has no calendar, time zones or date formatting; use chrono, time or jiff, store UTC, and convert for display.
  • thread::sleep waits at least the given time; timeouts such as recv_timeout and deadline loops avoid waiting forever.
  • Inject a Clock so tests can control time.

Next: Files and the Filesystem