Doctor David Anderson
Doctor David Anderson

Reputation: 274

Parsing hh:mm:ss time from stopwatch in 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.

Upvotes: 3

Views: 11909

Answers (4)

nav
nav

Reputation: 47

For anyone interested, I've created a go module that handles parsing HH:MM:SS strings to a time.Duration type.

You'll be able to do whatever kind of comparisons you need with time.Duration.

https://github.com/dannav/hhmmss

Upvotes: 1

Koala Yeung
Koala Yeung

Reputation: 7863

An alternative solution: https://play.golang.org/p/MHDLSGJIZd

package main

import (
    "fmt"
    "time"
)

// Parse a duration string of "hh:mm:ss" format
func Parse(str string) (time.Duration, error) {
    return time.ParseDuration(str[0:2] + "h" + str[3:5] + "m" + str[6:8] + "s")
}

// Sub subtract 2 durations
func Sub(d1, d2 time.Duration) time.Duration {
    epoch := time.Unix(0, 0)
    t1, t2 := epoch.Add(d1), epoch.Add(d2)
    return t1.Sub(t2)
}

func main() {
    var err error
    var d1, d2 time.Duration

    if d1, err = Parse("60:01:30"); err != nil {
        panic(err)
    }
    if d2, err = Parse("25:00:00"); err != nil {
        panic(err)
    }

    diff := Sub(d1, d2)
    fmt.Println(err, diff, diff.Seconds())
}

Upvotes: -1

Eugene Lisitsky
Eugene Lisitsky

Reputation: 12845

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

Upvotes: 11

dave
dave

Reputation: 64657

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
}

Upvotes: 2

Related Questions