您好,登录后才能下订单哦!
本篇文章为大家展示了python中怎么实现日期与时间戳的各种转换,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
datetime 和 time 两个模块,任意一个都能转换完成。
以下两个模块均列出示例:
# coding: utf-8from datetime import datetimeimport times = '2019-06-07 16:30:10'f = '%Y-%m-%d %H:%M:%S's2 = 'Fri Jun 7 16:30:10 2019'f2 = '%c'// 时间字符串转时间戳, 时间字串 s和format 对应// int(t) 转为整型t = datetime.strptime(s, f).timestamp() # 1559856210.0t2 = time.mktime(time.strptime(s, f)) # 1559856210.0t3 = time.mktime(time.strptime(s2, f2)) # 1559856210.0t4 = datetime.strptime(s2, f2).timestamp() # 1559856210.0t5 = datetime.strptime('2019-06-07', '%Y-%m-%d').timestamp() # 1559836800.0t6 = datetime.strptime('06/07/19', '%x').timestamp() # 1559836800.0 (06/07/2019, '%m/%d/%Y')print(t, t2, t3, t4, t5, t6, "\n")ut = 1559896210# 时间戳转为时间字符串d = datetime.fromtimestamp(ut) # 2019-06-07 16:30:10d2 = time.strftime(f, time.localtime(ut)) # 2019-06-07 16:30:10d3 = time.ctime(ut) # Fri Jun 7 16:30:10 2019d4 = datetime.fromtimestamp(ut).ctime() # Fri Jun 7 16:30:10 2019d5 = time.strftime('%Y-%m-%d', time.localtime(ut)) # 2019-06-07 (05:23:30, %H:%M:%S)d6 = datetime.fromtimestamp(ut).date() # 2019-06-07d7 = datetime.fromtimestamp(ut).time() # 16:30:10d8 = time.strftime('%x', time.localtime(ut)) # 06/07/19d9 = time.strftime('%X', time.localtime(ut)) # 16:30:10dd = datetime.fromtimestamp(ut).strftime('%x') # 06/07/19 [(16:30:10, %X), (Fri Jun 7 16:30:10 2019, %c)]print(d, d2, d3, d4, d5, d6, d7, d8, d9, dd, "\n")# 格式转换# 将 2019-06-07 16:30:10 转为 Fri Jun 7 16:30:10 2019# (16:30:10, %X)transf = datetime.strptime(s, f).strftime(f2)# 将 Fri Jun 7 16:30:10 2019 转为 2019-06-07# (2019-06-07 16:30:10, %Y-%m-%d %H:%M:%S)transf2 = datetime.strptime(s2, f2).strftime('%Y-%m-%d')# 将 2019-06-07 16:30:10 转为 Fri Jun 7 16:30:10 2019# (2019-06-07 16:30:10, %Y-%m-%d %H:%M:%S)transf3 = time.strftime('%c', time.strptime(s, f))# 将 Fri Jun 7 16:30:10 2019 转为 2019-06-07 16:30:10transf4 = time.strftime(f, time.strptime(s2, f2))print(transf, transf2, transf3, transf4)
上述内容就是python中怎么实现日期与时间戳的各种转换,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。