drn9573
2017-01-12 15:47 阅读 149
已采纳

如何解析时间长度不同的字符串时间戳?

I have a slice of values holding timestamps of different length. Most of them look like this:

2006-01-02T15:04:05.000000Z

but some of them are shorter:

2006-01-02T15:04:05.00000Z
2006-01-02T15:04:05.0000Z

If I do:

str := dataSlice[j][0].(string)
layout := "2006-01-02T15:04:05.000000Z"
t, err := time.Parse(layout, str)

I get errors like:

parsing time "2016-10-23T02:38:45.25986Z" as "2006-01-02T15:04:05.000000Z": cannot parse "" as ".000000"
parsing time "2016-10-23T21:43:59.0175Z" as "2006-01-02T15:04:05.000000Z": cannot parse ".0175Z" as ".000000"

I want to parse them exactly like they originally are. How can I dynamically switch the layout corresponding to the length? (And why do the error messages differ?)

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    dqunzip3183 dqunzip3183 2017-01-12 16:08

    For time layouts, if the fractional seconds are optional, use 9 instead of 0 in the layout. For example, 2006-01-02T15:04:05.00000Z matches only times with 5 digits after the decimal place. However, 2006-01-02T15:04:05.9Z matches a time with any number of digits after the decimal, including zero.

    https://play.golang.org/p/QMD28aqv9E

    The Time.Format documentation provides examples, the last one of which explains this behavior.

    点赞 评论 复制链接分享
  • dongzhun4898 dongzhun4898 2017-01-12 16:08

    Just replace 000000 with 999999:

    layout := "2006-01-02T15:04:05.999999Z"
    

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

    点赞 评论 复制链接分享

相关推荐