get system uptime in rust

To get the system uptime in Rust, we can use the chrono and std crates. Here's an example code to obtain the system uptime in seconds:

main.rs
use std::fs::File;
use std::io::Read;
use std::time::Duration;
use chrono::prelude::*;

fn get_uptime() -> Duration {
    let mut uptime_str = String::new();
    let mut f = File::open("/proc/uptime").expect("Failed to open /proc/uptime");
    f.read_to_string(&mut uptime_str).expect("Failed to read /proc/uptime");

    let uptime_secs = uptime_str.split('.').next().expect("Malformed /proc/uptime").parse::<u64>().expect("Malformed /proc/uptime");
    Duration::from_secs(uptime_secs)
}

fn main() {
    let uptime_duration = get_uptime();
    let datetime = Utc::now() - uptime_duration;
    println!("System started at {}", datetime.to_rfc2822());
}
655 chars
20 lines

This code reads the /proc/uptime file in Linux, which contains the system uptime in seconds and fractions of seconds. It then parses the uptime seconds as a u64 integer and returns it as a Duration object. Finally, we can subtract the uptime duration from the current UTC time to obtain the datetime when the system was started.

gistlibby LogSnag