[Golang] Get Last System Boot Time
This post shows you how to get last Ubuntu Linux system boot/restrart time in Go via executing shell command.
To get last system boot time, we use who -b command [1] [2]:
To get timezone of the system, we use date +%Z command [3] [4]:
Then we combine the boot time and timezone string. Call time.Parse to parse the string and return time.Time struct for further processing.
package main
import (
"fmt"
"os/exec"
"strings"
"time"
)
func getLastBootTime() string {
out, err := exec.Command("who", "-b").Output()
if err != nil {
panic(err)
}
t := strings.TrimSpace(string(out))
t = strings.TrimPrefix(t, "system boot")
t = strings.TrimSpace(t)
return t
}
func getTimezone() string {
out, err := exec.Command("date", "+%Z").Output()
if err != nil {
panic(err)
}
return strings.TrimSpace(string(out))
}
func getLastSystemBootTime() (time.Time, error) {
return time.Parse(`2006-01-02 15:04MST`, getLastBootTime()+getTimezone())
}
func main() {
t, err := getLastSystemBootTime()
if err != nil {
panic(err)
}
fmt.Println(t.Format(time.RFC3339))
}
Output from my Ubuntu Linux system:
2018-04-05T17:56:00+08:00
Tested on: Ubuntu Linux 17.10, Go 1.10.1
References
[1] |
[2] | Linux Find Out Last System Reboot Time and Date Command - nixCraft |
[3] |
[4] | How to Check Timezone in Linux |