如何解析时间长度不同的字符串时间戳?
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?)
我有一小部分值保存着不同长度的时间戳。 其中大多数看起来像这样: p>
2006-01-02T15:04:05.000000Z
code> pre>
,但其中一些较短: p>
2006-01-02T15:04:05.00000Z
2006-01-02T15:04:05.0000Z
code> pre>
如果我这样做: p>
str:= dataSlice [j] [0]。(string)
layout:=“ 2006-01-02T15:04:05.000000Z”
t,err:= time.Parse(layout,str)
code> pre>
我收到类似以下错误: p>
解析时间“ 2016-10 -23T02:38:45.25986Z“设为” 2006-01-02T15:04:05.000000Z“:无法将”“解析为” .000000“
解析时间” 2016-10-23T21:43:59.0175Z“设为” 2006- 01-02T15:04:05.000000Z“:无法将” .0175Z“解析为” .000000“
code> pre>
我想像它们原本一样解析它们。\ n我如何动态地切换与长度相对应的布局?
(为什么错误消息会有所不同?) p>
div>
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.
Just replace 000000
with 999999
:
layout := "2006-01-02T15:04:05.999999Z"
Playground: https://play.golang.org/p/Wd7kXIpoWO.