python time模块计算时间之间的差距
练习题
1. 当前月1号对应的0点的时间戳
1
2
3
4
5
6
7
|
# 定义一个当前月分的一号0点字符串格式的时间 now_time = time.strftime( '%Y-%m-01 00:00:00' ) # 将格式化时间转换为结构化时间 jiegou = time.strptime(now_time, '%Y-%m-%d %H:%M:%S' ) # 将结构化时间转换为对应的时间戳 shijiancuo = time.mktime(jiegou) print ( '%s对应的时间戳为%s' % (now_time,shijiancuo)) |
2. n1的时间 n2的时间 n2 - n1的时间经历里多少年 月 日 时 分 秒
思想:需要首先将两个字符串时间转换为时间戳格式,然后相减,再转换为结构化时间,然后减去时间戳最开始时间(伦敦时间:1970/01/01 00:00:00)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
import time n1 = '2019-07-18 20:07:56' n2 = '2019-07-19 22:03:12' # 格式化时间转换为结构化时间 struct_time1, struct_time2 = time.strptime(n1, '%Y-%m-%d %H:%M:%S' ), time.strptime(n2, '%Y-%m-%d %H:%M:%S' ) # 结构化时间转换为时间戳格式 struct_time1, struct_time2 = time.mktime(struct_time1), time.mktime(struct_time2) # 差的时间戳 diff_time = struct_time2 - struct_time1 # 将计算出来的时间戳转换为结构化时间 struct_time = time.gmtime(diff_time) # 减去时间戳最开始的时间 并格式化输出 print ( '过去了{0}年{1}月{2}日{3}小时{4}分钟{5}秒' . format ( struct_time.tm_year - 1970 , struct_time.tm_mon - 1 , struct_time.tm_mday - 1 , struct_time.tm_hour, struct_time.tm_min, struct_time.tm_sec )) |
补充:python-time模块计算时间差
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import time # t = time.time() # print(t) # z = time.strftime('%Y-%m-%d %H:%M:%S') # print(z) # # a = time.localtime(time.time()) # print(a) nowtime = time.time() longtime = time.strptime( '2018-10-17 6:0:0' , '%Y-%m-%d %H:%M:%S' ) print (longtime) d = time.mktime(longtime) print (d) new = nowtime - d print (new) s = time.localtime(new) ss = time.strftime( '%H:%M:%S' ,time.localtime(new)) print (ss) |
到此这篇关于python time模块计算时间之间的差距的文章就介绍到这了,更多相关python time模块计算时间内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/qq_36850246/article/details/99322303