在Go中以不同的分数秒长度进行解析

I am parsing a timestamp from a DB. My layout is the following:

layout = "2006-01-02 15:04:05.000000000 -0700 MST"

pipelineTS, err := time.Parse(layout, rawPipelineTS)

The issue is that sometimes the fractional seconds are not 9 digits, for example:

2018-12-18 15:25:08.73728596 +0000 UTC  

When it finds a value like this, it errors out. Any ideas on how to fix this? The timestamps come from a DB table. I need it to take any number of fractional second digits.

Package time

A decimal point followed by one or more zeros represents a fractional second, printed to the given number of decimal places. A decimal point followed by one or more nines represents a fractional second, printed to the given number of decimal places, with trailing zeros removed.


Use nines, not zeros, for the layout fractional seconds.

For example,

package main

import (
    "fmt"
    "time"
)

func main() {
    layout := "2006-01-02 15:04:05.999999999 -0700 MST"

    input := "2018-12-18 15:25:08.73728596 +0000 UTC" // 8 digits
    t, err := time.Parse(layout, input)
    fmt.Println(t, err)

    input = "2018-12-18 15:25:08.7372 +0000 UTC" // 4 digits
    t, err = time.Parse(layout, input)
    fmt.Println(t, err)

    input = "2018-12-18 15:25:08 +0000 UTC" // 0 digits
    t, err = time.Parse(layout, input)
    fmt.Println(t, err)
}

Playground: https://play.golang.org/p/j4WBmz3ENke

Output:

2018-12-18 15:25:08.73728596 +0000 UTC <nil>
2018-12-18 15:25:08.7372 +0000 UTC <nil>
2018-12-18 15:25:08 +0000 UTC <nil>