How to get last-accessed date and time of file in Go?

By casting os.FileInfo to *syscall.Stat_t:

package main

import ( "fmt"; "log"; "os"; "syscall"; "time" )

func main() {
    for _, arg := range os.Args[1:] {
        fileinfo, err := os.Stat(arg)
        if err != nil {
            log.Fatal(err)
        }
        atime := fileinfo.Sys().(*syscall.Stat_t).Atim
        fmt.Println(time.Unix(atime.Sec, atime.Nsec))
    }
}

Alternatively, after the Stat you can also do

statinfo.ModTime()

Also you can use Format() on it, should you need it eg for a webserver

see https://gist.github.com/alexisrobert/982674


You can use os.Stat to get a FileInfo struct which also contains the last access time (as well as the last modified and the last status change time).

info, err := os.Stat("example.txt")
if err != nil {
     // TODO: handle errors (e.g. file not found)
}
// info.Atime_ns now contains the last access time
// (in nanoseconds since the unix epoch)

After that, you can use time.Nanoseconds to get the current time (also in nanoseconds since the unix epoch, January 1, 1970 00:00:00 UTC). To get the duration in nanoseconds, just subtract those two values:

duration := time.Nanoseconds() - info.Atime_ns