Jerry2019

计算时间差

需求:如-2018年1月11日 11:11:11 到现在的时间差,请打印成:已经过去-年-月-日-时-分-秒

这是笔者自己的思路

#思路
\'\'\'
假如
开始时间是2018-01-01 11:11:11
结束时间是2019-02-02 22:22:22
计算这两个过去的时间差
将开始时间转换为时间戳
将结束时间转换为时间戳
结束时间减去开始时间等于时间差
这个时间差是时间戳
将时间戳转换为元组(struct_time),获得结构化时间
将结构化时间减去时间戳的开始时间1970即可以获得相差的年
直接格式化输出时间差
\'\'\'
# 从格式化时间字符串 --使用strptime-->元组(struct_time)--使用mktime--> 时间搓
import time
# 得出开始时间的时间搓
start_time =time.strptime(\'2018-01-01 11:11:11\',\'%Y-%m-%d %H:%M:%S\')
print(start_time)
start_time = time.mktime(start_time)
print(start_time)
# 得出结束时间的时间搓
end_time = time.strptime(\'2019-02-02 22:22:22\',\'%Y-%m-%d %H:%M:%S\')
print(end_time)
end_time = time.mktime(end_time)
print(end_time)
# 计算时间戳的差
the_time = end_time - start_time
print(the_time)
# 将时间差--使用localtime|gmtime-->元组(struct_time)-->打印时间差
the_time = time.localtime(the_time)
print(the_time)
# 因为时间戳是从1970-01-01 00:00:00开始计算,所以获得的年是1971年,只需减去1970年则可以获得时间差
# 将时间差转为格式化字符串
# the_time = time.strftime(\'%Y-%m-%d %H:%M:%S\',the_time)
# print(the_time)
print(\'过去%d年%d个月%d日%d个小时%d分%d秒\'%(the_time.tm_year-1970,the_time.tm_mon,
                                                  the_time.tm_mday,the_time.tm_hour,the_time.tm_min,
                                                  the_time.tm_sec))
笔者的思路

这是视频教学的代码

import time
true_time=time.mktime(time.strptime(\'2017-09-11 08:30:00\',\'%Y-%m-%d %H:%M:%S\'))
time_now=time.mktime(time.strptime(\'2017-09-12 11:00:00\',\'%Y-%m-%d %H:%M:%S\'))
dif_time=time_now-true_time
struct_time=time.gmtime(dif_time)
print(\'过去了%d年%d月%d天%d小时%d分钟%d秒\'%(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))
计算时间差

 

分类:

技术点:

相关文章:

  • 2021-12-25
  • 2021-11-14
  • 2021-12-19
  • 2021-11-14
  • 2021-11-14
  • 2021-12-19
  • 2021-12-09
  • 2021-10-07
猜你喜欢
  • 2021-11-24
  • 2021-11-24
相关资源
相似解决方案