Golang – 格式化和存储后时间戳丢失年份

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

Golang - Timestamp losing year after formatting and storage

问题

我正在使用Go运行时将实体存储在Appengine Datastore中,并按它们添加的时间进行排序;为了将时间戳存储在键中,我使用time.Time.String()方法格式化时间戳,并将字符串版本存储为键。

为了在检索时再次获取时间,我使用time.Parse:

time.Parse("2006-01-02 15:04:05.000000000 +0000 UTC", the_timestamp)

在独立于应用程序的单元测试中(使用命令行-goapp test),我的测试可以完整地检索时间戳,没有问题。

但是,当我将执行此操作的包导入到一个appengine应用程序中并进行测试(使用命令行-goapp serve),时间戳的年份字段被设置为"0000"。

英文:

I am using the Go runtime to store entities in the Appengine Datastore sequenced by the time they were added; to store the timestamp in the key I am formatting the timestamp using the time.Time.String() method and storing the string version as the key.

To get the Time back again on retrieval I use time.Parse:

time.Parse("2006-01-02 15:04:05.000000000 +0000 UTC", the_timestamp)

In unit testing this functionality independent of an app (using cmdline - goapp test) my tests retrieve the timestamp in its entirety no problem.

But when I import the package doing this into an appengine app and test it (using cmdline - goapp serve) the timestamp is stored with its Year field set to "0000"

答案1

得分: 3

当你将时间转换为字符串后保存到数据存储中时,时间末尾的额外的0会被移除。

所以,

2009-11-10 23:00:00.12300000 +0000 UTC

会被转换为

2009-11-10 23:00:00.123 +0000 UTC

现在当你从数据存储中检索它并使用Parse函数时,它会尝试匹配小数点后的8位数字。因此会出现错误。

所以,在将时间转换为字符串时,你需要格式化字符串,以便不丢失0。

const layout = "2006-01-02 15:04:05.000000000 +0000 UTC"
t := time.Now()
tFormat := t.Format(layout)

http://play.golang.org/p/elr28mfMo8

英文:

When you are converting your time to string before saving into datastore, the extra 0s at the end of time are removed.
So,

2009-11-10 23:00:00.12300000 +0000 UTC

is converted into

2009-11-10 23:00:00.123 +0000 UTC

Now when you retrieve it from datastore and use the Parse function, it tries to match upto 8 digits after decimal. Hence the error.

So, while converting the time into string, you need to Format the string so that 0s are not lost.

const layout = "2006-01-02 15:04:05.000000000 +0000 UTC"
t := time.Now()
tFormat := t.Format(layout)

http://play.golang.org/p/elr28mfMo8

huangapple
  • 本文由 发表于 2014年9月1日 15:48:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/25601095.html
匿名

发表评论

匿名网友

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

确定