python time模块计算时间之间的差距(练习题)

后端开发   发布日期:2023年05月29日   浏览次数:50

python time模块计算时间之间的差距

练习题

1. 当前月1号对应的0点的时间戳

  1. # 定义一个当前月分的一号0点字符串格式的时间
  2. now_time = time.strftime('%Y-%m-01 00:00:00')
  3. # 将格式化时间转换为结构化时间
  4. jiegou = time.strptime(now_time, '%Y-%m-%d %H:%M:%S')
  5. # 将结构化时间转换为对应的时间戳
  6. shijiancuo = time.mktime(jiegou)
  7. print('%s对应的时间戳为%s'%(now_time,shijiancuo))

2. n1的时间 n2的时间 n2 - n1的时间经历里多少年 月 日 时 分 秒

思想:需要首先将两个字符串时间转换为时间戳格式,然后相减,再转换为结构化时间,然后减去时间戳最开始时间(伦敦时间:1970/01/01 00:00:00)

  1. import time
  2. n1 = '2019-07-18 20:07:56'
  3. n2 = '2019-07-19 22:03:12'
  4. # 格式化时间转换为结构化时间
  5. struct_time1, struct_time2 = time.strptime(n1, '%Y-%m-%d %H:%M:%S'), time.strptime(n2, '%Y-%m-%d %H:%M:%S')
  6. # 结构化时间转换为时间戳格式
  7. struct_time1, struct_time2 = time.mktime(struct_time1), time.mktime(struct_time2)
  8. # 差的时间戳
  9. diff_time = struct_time2 - struct_time1
  10. # 将计算出来的时间戳转换为结构化时间
  11. struct_time = time.gmtime(diff_time)
  12. # 减去时间戳最开始的时间 并格式化输出
  13. print('过去了{0}年{1}月{2}日{3}小时{4}分钟{5}秒'.format(
  14. struct_time.tm_year-1970,
  15. struct_time.tm_mon-1,
  16. struct_time.tm_mday-1,
  17. struct_time.tm_hour,
  18. struct_time.tm_min,
  19. struct_time.tm_sec
  20. ))

补充:python-time模块计算时间差

  1. import time
  2. # t = time.time()
  3. # print(t)
  4. # z = time.strftime('%Y-%m-%d %H:%M:%S')
  5. # print(z)
  6. #
  7. # a = time.localtime(time.time())
  8. # print(a)
  9. nowtime = time.time()
  10. longtime = time.strptime('2018-10-17 6:0:0','%Y-%m-%d %H:%M:%S')
  11. print(longtime)
  12. d = time.mktime(longtime)
  13. print(d)
  14. new = nowtime - d
  15. print(new)
  16. s = time.localtime(new)
  17. ss = time.strftime('%H:%M:%S',time.localtime(new))
  18. print(ss)
原文地址:https://blog.csdn.net/qq_36850246/article/details/99322303

以上就是python time模块计算时间之间的差距(练习题)的详细内容,更多关于python time模块计算时间之间的差距(练习题)的资料请关注九品源码其它相关文章!