Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse string timestamps of different length to time?

Tags:

timestamp

go

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

like image 561
myNickname Avatar asked Sep 11 '25 17:09

myNickname


2 Answers

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.

like image 151
Kaedys Avatar answered Sep 13 '25 08:09

Kaedys


Just replace 000000 with 999999:

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

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

like image 23
Ainar-G Avatar answered Sep 13 '25 07:09

Ainar-G