get system boot time in minutes in go

To get the system boot time in minutes in Go, we can use the os.Stat() function to get the Sys() information of the /proc directory on Linux systems.

main.go
package main

import (
	"fmt"
	"os"
	"time"
)

func main() {
	stat, err := os.Stat("/proc")
	if err != nil {
		panic(err)
	}

	uptime := stat.Sys().(*syscall.Stat_t).Ctim

	bootTime := time.Unix(uptime.Unix()).Format(time.RFC3339)

	now := time.Now().Unix()
	elapsed := now - uptime.Unix()

	fmt.Printf("System has been running for %d minutes since %s\n", elapsed/60, bootTime)
}
380 chars
24 lines

In this code, we first get the system Stat() information of the /proc directory. We then extract the system boot time from the Sys() information using the uptime field.

We then convert the boot time to a human-readable format using time.Unix() and time.Format(). Finally, we calculate the current system uptime in minutes by subtracting the boot time from the current time, and divide it by 60.

related categories

gistlibby LogSnag