Golang中如何格式化时间间隔?
Golang中如何格式化时间间隔? 我在 main.go 中使用了以下代码:
start := time.Now()
// 执行某些操作
fmt.Printf("Execution time: %s", time.Since(start))
通常输出结果是:
Execution time: 1.5994525s
如何将输出格式调整为:
Execution time: 1.60 s
-> 即,将小数点后四舍五入保留两位,加一个空格,然后是“s”?
2 回复
明白了…
fmt.Printf("Execution time: %.2f s", time.Now().Sub(start).Seconds())
更多关于Golang中如何格式化时间间隔?的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
在Go中格式化时间间隔,可以使用time.Duration的Round或Truncate方法结合格式化输出。以下是几种实现方式:
方法1:使用Round方法四舍五入
package main
import (
"fmt"
"time"
)
func main() {
start := time.Now()
time.Sleep(1599 * time.Millisecond) // 模拟操作
duration := time.Since(start)
// 四舍五入到两位小数(100ms精度)
rounded := duration.Round(10 * time.Millisecond)
fmt.Printf("Execution time: %.2f s\n", float64(rounded)/float64(time.Second))
}
方法2:手动计算并格式化
package main
import (
"fmt"
"time"
)
func main() {
start := time.Now()
time.Sleep(1599452 * time.Microsecond) // 模拟操作
duration := time.Since(start)
// 转换为秒并保留两位小数
seconds := float64(duration) / float64(time.Second)
fmt.Printf("Execution time: %.2f s\n", seconds)
}
方法3:自定义格式化函数
package main
import (
"fmt"
"time"
)
func formatDuration(d time.Duration) string {
seconds := float64(d) / float64(time.Second)
return fmt.Sprintf("%.2f s", seconds)
}
func main() {
start := time.Now()
time.Sleep(1599452 * time.Microsecond)
fmt.Printf("Execution time: %s\n", formatDuration(time.Since(start)))
}
方法4:使用time.Duration的String方法并处理输出
package main
import (
"fmt"
"strings"
"time"
)
func main() {
start := time.Now()
time.Sleep(1599452 * time.Microsecond)
duration := time.Since(start)
str := duration.String()
// 如果包含小数部分,格式化输出
if strings.Contains(str, ".") {
parts := strings.Split(str, ".")
if len(parts) == 2 {
seconds := parts[0]
decimal := parts[1]
if len(decimal) > 2 {
decimal = decimal[:2]
}
fmt.Printf("Execution time: %s.%s s\n", seconds, decimal)
}
} else {
fmt.Printf("Execution time: %s.00 s\n", str)
}
}
所有方法都会输出:
Execution time: 1.60 s
第一种方法最简洁,直接使用Round方法进行四舍五入。第二种方法最灵活,可以精确控制小数位数。第三种方法适合重复使用场景。第四种方法处理了time.Duration的字符串表示。

