在golang中,Time.Format()从小数部分中删除尾随零

时间:2017-11-07 18:23:04

标签: go

如何防止Time.Format()从小数部分删除尾随零?我有以下单元测试失败。

set_list = set(map(lambda x: (x[0], x[1]), a))

result = [
    [m[0], m[1], sum([y[2] for y in a if (y[0], y[1]) == m])] 
    for m in set_list
]

输出:

package main

import (
    "testing"
    "time"
)

func TestTimeFormatting(t *testing.T) {
    timestamp := time.Date(2017, 1,2, 3, 4, 5, 600000*1000, time.UTC)
    timestamp_string := timestamp.Format("2006-01-02T15:04:05.999-07:00")
    expected := "2017-01-02T03:04:05.600+00:00"

    if expected != timestamp_string {
        t.Errorf("Invalid timestamp formating, expected %v, got %v", expected, timestamp_string)
    }
}

知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:4)

啊,文档中有没有。如果你想保留零,应该使用000而不是999。

package main

import (
    "testing"
    "time"
)

func TestTimeFormatting(t *testing.T) {
    timestamp := time.Date(2017, 1,2, 3, 4, 5, 600000*1000, time.UTC)
    timestamp_string := timestamp.Format("2006-01-02T15:04:05.000-07:00")
    expected := "2017-01-02T03:04:05.600+00:00"

    if expected != timestamp_string {
        t.Errorf("Invalid timestamp formating, expected %v, got %v", expected, timestamp_string)
    }
}