Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing hh:mm:ss time from stopwatch in Go?

Tags:

time

go

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.

like image 446
Doctor David Anderson Avatar asked Dec 12 '25 04:12

Doctor David Anderson


2 Answers

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

like image 163
Eugene Lisitsky Avatar answered Dec 14 '25 01:12

Eugene Lisitsky


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
}
like image 22
dave Avatar answered Dec 14 '25 00:12

dave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!