英文:
How do I parse string timestamps of different length to time?
问题
我有一个包含不同长度时间戳的值的切片。大部分看起来像这样:
2006-01-02T15:04:05.000000Z
但有些较短:
2006-01-02T15:04:05.00000Z
2006-01-02T15:04:05.0000Z
如果我执行以下操作:
str := dataSlice[j][0].(string)
layout := "2006-01-02T15:04:05.000000Z"
t, err := time.Parse(layout, str)
我会得到类似以下的错误:
parsing time "2016-10-23T02:38:45.25986Z" as "2006-01-02T15:04:05.000000Z": 无法将""解析为".000000"
parsing time "2016-10-23T21:43:59.0175Z" as "2006-01-02T15:04:05.000000Z": 无法将".0175Z"解析为".000000"
我想要按照它们最初的格式进行解析。如何根据长度动态切换布局?(为什么错误消息不同?)
英文:
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?)
答案1
得分: 4
对于时间布局,如果小数秒是可选的,请在布局中使用9
而不是0
。例如,2006-01-02T15:04:05.00000Z
只匹配小数点后有5位数字的时间。然而,2006-01-02T15:04:05.9Z
匹配小数点后的任意位数,包括零。
Time.Format文档提供了示例,其中最后一个示例解释了这种行为。
英文:
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.
答案2
得分: 1
只需将000000
替换为999999
:
layout := "2006-01-02T15:04:05.999999Z"
Playground: https://play.golang.org/p/Wd7kXIpoWO.
英文:
Just replace 000000
with 999999
:
layout := "2006-01-02T15:04:05.999999Z"
Playground: https://play.golang.org/p/Wd7kXIpoWO.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论