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

huangapple go评论94阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2017年1月12日 23:47:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/41617401.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定