Get the time elapsed since the epoch using only std

time SystemTime UNIX_EPOCH epoch

In this example using only std, the standard library we fetch the time elapsed since the epoch (which is 1970 January 1 on Unix/Linux systems).

examples/epoch/src/main.rs

use std::time::{SystemTime, UNIX_EPOCH};
fn main() {
    let start = SystemTime::now();
    let since_the_epoch = start
        .duration_since(UNIX_EPOCH)
        .expect("Time went backwards");

    println!("start:           {start:?}", );
    println!("since_the_epoch: {since_the_epoch:?}");
    println!("as_nanos:        {}", since_the_epoch.as_nanos());
    println!("as_micros:       {}", since_the_epoch.as_micros());
    println!("as_millis:       {}", since_the_epoch.as_millis());
    println!("as_secs:         {}", since_the_epoch.as_secs());
    println!("as_secs_f32:     {}", since_the_epoch.as_secs_f32());
    println!("as_secs_f64:     {}", since_the_epoch.as_secs_f64());
}


Running on Linux this is the output:

$ cargo run -q

start:           SystemTime { tv_sec: 1707553108, tv_nsec: 951575643 }
since_the_epoch: 1707553108.951575643s
as_nanos:        1707553108951575643
as_micros:       1707553108951575
as_millis:       1707553108951
as_secs:         1707553108
as_secs_f32:     1707553200
as_secs_f64:     1707553108.9515758

Related Pages

Clap - Showing the description in the help using the about command

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo