I have a series of stopwatch-like timestamps in a logfile formatted as hh:mm:ss, e.g. "00:03:30". How would I go about parsing such timestamps in Golang such that I could find the difference between two time intervals?
For example, substituting 00:03:30 and 00:03:00 should return 00:00:30 or 30.
You may subtract one time from another.
package main
import (
"fmt"
"time"
)
func main() {
t1, err := time.Parse("15:04:05", "03:00:30")
t2, err := time.Parse("15:04:05", "03:00:00")
fmt.Println(err, t1.Sub(t2), t1.Sub(t2).Seconds())
}
Working example - https://play.golang.org/p/VegXLBvfnM
UPDATE: How to cope with durations over 24:00:00? This way they can be parsed manually:
func Parse(st string) (int, error) {
var h, m, s int
n, err := fmt.Sscanf(st, "%d:%d:%d", &h, &m, &s)
fmt.Print(n, err)
if err != nil || n != 3 {
return 0, err
}
return h*3600 + m*60 + s, nil
}
https://play.golang.org/p/HHSRHzaGqT
Just use time.Parse and time.Sub
https://play.golang.org/p/qhYm4OEon8
package main
import (
"fmt"
"time"
)
func main() {
t1, _ := time.Parse("03:04:05", "00:03:30")
t2, _ := time.Parse("03:04:05", "00:03:00")
fmt.Println(t1.Sub(t2)) //30s
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With