4

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?)

myNickname
  • 63
  • 5
  • Are the fractional portions all `0`s, or do you need sub-second resolution if they're not? It would be easy to just strip that out of the string on all timestamps before parsing. – JimB Jan 12 '17 at 15:51
  • Unfortunately they are not all `0` s, samples: `2016-07-04T09:30:33.031979Z` `2016-10-23T22:01:01.41305Z` `2016-10-23T14:50:55.0671Z` – myNickname Jan 12 '17 at 16:01

2 Answers2

4

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.

Kaedys
  • 9,600
  • 1
  • 33
  • 40
1

Just replace 000000 with 999999:

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

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

Ainar-G
  • 34,563
  • 13
  • 93
  • 119