dounai6626 2014-09-01 07:48
浏览 117
已采纳

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

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条回答 默认 最新

  • dongpu2727 2014-09-01 11:45
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题