简体   繁体   English

如何在 go 中使用 time.Parse() 逗号分隔毫秒

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

I have logs with timestamps that look like "2020-05-08 22:02:00,845".我的日志的时间戳看起来像“2020-05-08 22:02:00,845”。 They have comma separated milliseconds, which is what is giving time.Parse issues.他们有逗号分隔的毫秒,这就是给 time.Parse 问题。 I can't seem to figure out how to make time.Parse happy with it.我似乎无法弄清楚如何让 time.Parse 满意。 Here is sample code that produces the error in go version go1.13.4 darwin/amd64 (and in the playground linked below);这是在 go 版本 go1.13.4 darwin/amd64 (以及下面链接的操场)中产生错误的示例代码;

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这里是go 操场中代码的链接

So what would a format look like to parse this?那么解析这个格式会是什么样子呢? Thanks for your help.谢谢你的帮助。

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.该行为记录如下:“小数秒通过在布局字符串的秒部分的末尾添加句点和零来表示,如在“15:04:05.000”中以毫秒精度格式化时间戳。

Workaround for that would be replacing "," with "."解决方法是将","替换为"."

package main package 主

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这里是游乐场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM