golang中time包之时间间隔格式化和秒、毫秒、纳秒等时间戳格式输出的方法实例
亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《golang中time包之时间间隔格式化和秒、毫秒、纳秒等时间戳格式输出的方法实例》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下go语言time包、格式化,希望所有认真读完的童鞋们,都有实质性的提高。
获取当前时间的年、月、日、时、分、秒的方法如下:
// 获取当前时间
now := time.Now()
// 当前时间的年、月、日、小时、分钟、秒和纳秒都可以通过现有接口直接获取
year := now.Year()
month := now.Month()
day := now.Day()
hour := now.Hour()
minute := now.Minute()
second := now.Second()
nanosecond := now.Nanosecond()
// 当前时间的微秒和毫秒是通过纳秒计算生成
microsecond := nanosecond / 1e3
millisecond := nanosecond / 1e6
fmt.Println(now.Format("2006-01-02 15:04:05.000000000"))
fmt.Println(year, month, day, hour, minute, second, nanosecond, microsecond, millisecond)
运行结果如下:
# 当前时间格式输出
2022-06-09 19:25:52.022598620
2022 June 9 19 25 52 22598620 22598 22
获取从1970到现在经过的时间的方法如下:
// 获取从1970经过的时间,秒和纳秒都可以通过现有接口直接获取
sec := now.Unix() // 时间戳位数为10
ms := now.UnixMilli() // 时间戳位数为13
us := now.UnixMicro() // 时间戳位数为16
ns := now.UnixNano() // 时间戳位数为19
fmt.Printf("sec:%v\n ms:%v\n us:%v\n ns:%v\n", sec, ms, us, ns)
运行结果如下:
# 1970经过的时间格式输出
sec:1654773952
ms:1654773952022
us:1654773952022598
ns:1654773952022598620
时间间隔格式化输出方法:
// 时间间隔返回的是time.Duration,下面以1h1m1s1ms1us1ns的时间间隔举例,测试各种格式的打印效果
duration := 1*time.Hour + 1*time.Minute + 1*time.Second +
1*time.Millisecond + 1*time.Microsecond + 1*time.Nanosecond
// 直接使用%v打印,不转换sec、ms或其他。
fmt.Printf("duration:%v\n", duration)
fmt.Printf("duration:%6v\n", duration)
fmt.Printf("duration:%.6v\n", duration)
fmt.Printf("duration:%.3v\n", duration)
// duration支持Hours()、 Minutes()、Seconds() 和
// Milliseconds()、Microseconds()、Nanoseconds()接口
// 前三个接口返回类型为float64可以通过0.3f打印小数点后的数,
// 后三个为int64,是整数,小数点后都是0
// 下面列举秒和毫秒的格式打印,其他时间单位可以参考秒和毫秒
// 秒的打印格式%f可以打印小数点后9位,精确到纳秒
fmt.Printf("duration:%vsec\n", duration.Seconds())
fmt.Printf("duration:%0.3fsec\n", duration.Seconds())
fmt.Printf("duration:%0.6fsec\n", duration.Seconds())
// 毫秒没有小数点,都是整数,转换成float后,小数点后都是0
fmt.Printf("duration:%vms\n", duration.Milliseconds())
fmt.Printf("duration:%.3dms\n", duration.Milliseconds())
fmt.Printf("duration:%.3fms\n", float64(duration.Milliseconds()))
}
行结果如下:
# 1h1m1s1ms1us1ns的时间间隔举例格式输出
# %v没有单位转换的时间输出
duration:1h1m1.001001001s
duration:1h1m1.001001001s
duration:1h1m1.
duration:1h1# 秒的格式输出
duration:3661.001001001sec
duration:3661.001sec
duration:3661.001001sec# 毫秒的格式输出
duration:3661001ms
duration:3661001ms
duration:3661001.000ms
通过测试程序可以看到:
1.没时间单位转换的格式输出,直接用%v能精确到ns,%.3V,只是对输出的字符串进行了切割。此处建议直接用%v即可。
2.对于秒的格式输出,%v精确到小数点9位,即纳秒。当然可以根据%f的格式调整,例如%.3f精确到毫秒
3.对于毫秒的格式输出,直接用%v或%d即可,转换成float64没有意义
一般在统计一个函数或一段程序运行了多长时间,一般建议使用第二种方式,转换成秒的格式输出,再根据精度调整%f的格式即可。
第一种方式有可能出现时间单位不统一,例如一个是分钟,一个是秒。
上面例子完成的代码如下:
package main
import (
"fmt"
"time"
)
func main() {
// 获取当前时间
now := time.Now()
// 当前时间的年、月、日、小时、分钟、秒和纳秒都可以通过现有接口直接获取
year := now.Year()
month := now.Month()
day := now.Day()
hour := now.Hour()
minute := now.Minute()
second := now.Second()
nanosecond := now.Nanosecond()
// 当前时间的微秒和毫秒是通过纳秒计算生成
microsecond := nanosecond / 1e3
millisecond := nanosecond / 1e6
fmt.Println(now.Format("2006-01-02 15:04:05.000000000"))
fmt.Println(year, month, day, hour, minute, second, nanosecond, microsecond, millisecond)
// 获取从1970经过的时间,秒和纳秒都可以通过现有接口直接获取
sec := now.Unix() // 时间戳位数为10
ms := now.UnixMilli() // 时间戳位数为13
us := now.UnixMicro() // 时间戳位数为16
ns := now.UnixNano() // 时间戳位数为19
fmt.Printf("sec:%v\n ms:%v\n us:%v\n ns:%v\n", sec, ms, us, ns)
// 时间间隔返回的是time.Duration,下面以1h1m1s1ms1us1ns的时间间隔举例,测试各种格式的打印效果
duration := 1*time.Hour + 1*time.Minute + 1*time.Second +
1*time.Millisecond + 1*time.Microsecond + 1*time.Nanosecond
// 直接使用%v打印,不转换sec、ms或其他。
fmt.Printf("duration:%v\n", duration)
fmt.Printf("duration:%6v\n", duration)
fmt.Printf("duration:%.6v\n", duration)
fmt.Printf("duration:%.3v\n", duration)
// duration支持Hours()、 Minutes()、Seconds() 和
// Milliseconds()、Microseconds()、Nanoseconds()接口
// 前三个接口返回类型为float64可以通过0.3f打印小数点后的数,
// 后三个为int64,是整数,小数点后都是0
// 下面列举秒和毫秒的格式打印,其他时间单位可以参考秒和毫秒
// 秒的打印格式%f可以打印小数点后9位,精确到纳秒
fmt.Printf("duration:%vsec\n", duration.Seconds())
fmt.Printf("duration:%0.3fsec\n", duration.Seconds())
fmt.Printf("duration:%0.6fsec\n", duration.Seconds())
// 毫秒没有小数点,都是整数,转换成float后,小数点后都是0
fmt.Printf("duration:%vms\n", duration.Milliseconds())
fmt.Printf("duration:%.3dms\n", duration.Milliseconds())
fmt.Printf("duration:%.3fms\n", float64(duration.Milliseconds()))
}
下面是时间间隔的时间单位转换的源码:
// time.go
// Nanoseconds returns the duration as an integer nanosecond count.
func (d Duration) Nanoseconds() int64 { return int64(d) }
// Microseconds returns the duration as an integer microsecond count.
func (d Duration) Microseconds() int64 { return int64(d) / 1e3 }
// Milliseconds returns the duration as an integer millisecond count.
func (d Duration) Milliseconds() int64 { return int64(d) / 1e6 }
// These methods return float64 because the dominant
// use case is for printing a floating point number like 1.5s, and
// a truncation to integer would make them not useful in those cases.
// Splitting the integer and fraction ourselves guarantees that
// converting the returned float64 to an integer rounds the same
// way that a pure integer conversion would have, even in cases
// where, say, float64(d.Nanoseconds())/1e9 would have rounded
// differently.
// Seconds returns the duration as a floating point number of seconds.
func (d Duration) Seconds() float64 {
sec := d / Second
nsec := d % Second
return float64(sec) + float64(nsec)/1e9
}
// Minutes returns the duration as a floating point number of minutes.
func (d Duration) Minutes() float64 {
min := d / Minute
nsec := d % Minute
return float64(min) + float64(nsec)/(60*1e9)
}
// Hours returns the duration as a floating point number of hours.
func (d Duration) Hours() float64 {
hour := d / Hour
nsec := d % Hour
return float64(hour) + float64(nsec)/(60*60*1e9)
}
补充:如果想格式化为12小时方式,需指定PM。
func formatDemo() {
now := time.Now()
// 格式化的模板为Go的出生时间2006年1月2号15点04分 Mon Jan
// 24小时制
fmt.Println(now.Format("2006-01-02 15:04:05.000 Mon Jan"))
// 12小时制
fmt.Println(now.Format("2006-01-02 03:04:05.000 PM Mon Jan"))
fmt.Println(now.Format("2006/01/02 15:04"))
fmt.Println(now.Format("15:04 2006/01/02"))
fmt.Println(now.Format("2006/01/02"))
}
总结
好了,本文到此结束,带大家了解了《golang中time包之时间间隔格式化和秒、毫秒、纳秒等时间戳格式输出的方法实例》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!
GoLang基础学习之go test测试
- 上一篇
- GoLang基础学习之go test测试
- 下一篇
- goland -sync/atomic原子操作小结
-
- 俊秀的保温杯
- 这篇技术文章太及时了,太全面了,很有用,码住,关注up主了!希望up主能多写Golang相关的文章。
- 2023-02-03 03:55:50
-
- Golang · Go教程 | 19小时前 | go标准库 · Go教程 · 字节处理 · 字节切片 Go 1.27 bytes.CutLast bytes.LastIndex 三返回值
- Go 1.27 bytes.CutLast 怎么封装:三返回值与 LastIndex 手写切片对比
- 276浏览 收藏
-
- Golang · Go教程 | 1天前 | 数字签名 · Go教程 · Go安全 · Go 1.27 crypto/ecdsa PrivateKey.Sign SignerOpts 哈希长度
- Go 1.27 ecdsa.PrivateKey.Sign 为什么检查哈希长度:SignerOpts 约束
- 212浏览 收藏
-
- Golang · Go教程 | 1天前 | 标准库 · Go教程 · 整数计算 · math/big RoundingMode Go 1.27 整数除法 Int.Divide
- Go 1.27 math/big.Int Divide 怎么选舍入:Trunc、Floor、Round 与 Ceil
- 202浏览 收藏
-
- Golang · Go教程 | 1天前 | HTTP服务 · Go教程 · 接口设计 · net/http Go 1.27 MaxHeaderValueCount MaxHeaderBytes HTTP安全
- Go 1.27 HTTP 请求头上限怎么设计:MaxHeaderValueCount 与 MaxHeaderBytes 配合
- 376浏览 收藏
-
- Golang · Go教程 | 1天前 | 标准库 · Go教程 · 工具开发 · 错误定位 · 语法分析 · Go 1.27 go/scanner Scanner.End token.Pos 语法诊断
- Go 1.27 go/scanner.Scanner.End 怎么定位 token 末端:起止位置与诊断范围
- 131浏览 收藏
-
- Golang · Go教程 | 1天前 | unsafe · Go教程 · Go升级 · go fix Go 1.27 unsafefuncs unsafe.Add
- Go 1.27 unsafefuncs 怎么改旧代码:函数指针转换的审查边界
- 368浏览 收藏
-
- Golang · Go教程 | 2天前 | go并发 · pprof · 故障排查 · Go教程 · 版本升级 · GODEBUG runtime/pprof Go 1.27 goroutine 标签 tracebacklabels
- Go 1.27 崩溃堆栈为什么多了 goroutine 标签:tracebacklabels 的取舍
- 174浏览 收藏
-
- Golang · Go教程 | 2天前 | 网络编程 · HTTP · go · 性能 · 连接复用 Go 1.27 http.Response.Body Response.Body.Close
- Go 1.27 http.Response.Body 关闭会自动排空什么:连接复用与异常边界
- 311浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- SuperCLUE
- SuperCLUE是权威的中文大语言模型综合评测基准,涵盖语言理解、知识应用、AI Agent智能体及安全性等12项核心能力。通过多轮对话与客观测试,定期发布榜单与技术报告,为模型研发、优化及行业选型提供科学依据。
- 101次使用
-
- C-Eval
- 深入了解C-Eval中文评估套件,涵盖52个学科与4级难度。本文详解其功能特点、Zero-shot/Few-shot使用方法及代码示例,助您全面评测LLM中文理解与泛化能力。
- 19次使用
-
- Gradio
- Gradio是一个用于构建机器学习和数据科学Web应用的开源Python库。支持快速创建交互界面,获Google、Meta等大厂青睐,适合模型演示、部署反馈及调试。
- 101次使用
-
- AutoGPT
- AutoGPT是基于GPT-4的开源AI代理平台,拥有超10万GitHub星标。本文介绍其低代码界面、自动化工作流功能、系统配置要求及安装步骤,助您高效部署和管理AI Agent。
- 106次使用
-
- 腾讯扣叮
- 腾讯扣叮是腾讯推出的6-18岁青少年编程学习平台,依托游戏与AI技术,提供图形化编程、3D创作、虚拟实验室及丰富赛事课程,助力培养计算思维与创新能力。
- 104次使用
-
- Go语言fmt.Sprintf格式化输出的语法与实例
- 2023-01-07 448浏览
-
- golang 格式化输入输出操作
- 2022-12-27 130浏览
-
- 详解Go 结构体格式化输出
- 2023-02-16 415浏览
-
- Go 字符串格式化的实例代码详解
- 2023-01-07 322浏览
-
- golang gorm中格式化时间问题详解
- 2023-02-24 438浏览

