how to time.Parse() comma separate milliseconds in go

Viewed 967

I have logs with timestamps that look like "2020-05-08 22:02:00,845". They have comma separated milliseconds, which is what is giving time.Parse issues. I can't seem to figure out how to make time.Parse happy with it. Here is sample code that produces the error in go version go1.13.4 darwin/amd64 (and in the playground linked below);

package main

import (
    "time"
)

func main() {
    ts := "2020-05-08 22:02:00,845"
    _, err := time.Parse("2006-01-02 15:04:05,000", ts)
    print(err.Error())
}

Running that code produces this error

parsing time "2020-05-08 22:02:00,845" as "2006-01-02 15:04:05,000": cannot parse "845" as ",000"

Here a link to the code in the go playground

So what would a format look like to parse this? Thanks for your help.

1 Answers

It's a bug already filed here

The behaviour is documented as such: "A fractional second is represented by adding a period and zeros to the end of the seconds section of layout string, as in "15:04:05.000" to format a time stamp with millisecond precision.

Workaround for that would be replacing "," with "."

package main

import (
    "time"
    "fmt"
    "strings"
)

func main() {
    ts := "2020-05-08 22:02:00,845"
    ts  =  strings.Replace(ts, ",", ".", -1)

    d, err := time.Parse("2006-01-02 15:04:05.000", ts)
    if err != nil{
        print(err.Error())
    }
    fmt.Println(d)
}

here is the Playground

Related