python利用时间戳计算时间差

主要是下面几步转化:

  •  1.由时间戳到时间元组struct_time

t1=time.localtime(stamp1)

  • 2.由时间元组到格式化时间字符串

 t1=time.strftime("%Y-%m-%d %H:%M:%S",t1)

  • 3.由格式化时间字符串到datetime对象的时间

time1=datetime.strptime(t1,"%Y-%m-%d %H:%M:%S")

  • 4.利用datetime的属性获取时间差
import datetime
def cal_time(stamp1,stamp2):
    t1=time.localtime(stamp1)
    t2 = time.localtime(stamp2)
    t1=time.strftime("%Y-%m-%d %H:%M:%S",t1)
    t2 = time.strftime("%Y-%m-%d %H:%M:%S", t2)
    time1=datetime.strptime(t1,"%Y-%m-%d %H:%M:%S")
    time2 = datetime.strptime(t2, "%Y-%m-%d %H:%M:%S")
    return (time2-time1).seconds

学习链接:https://cloud.tencent.com/developer/article/1387645 

                  https://blog.csdn.net/ljh0302/article/details/54882750

发布了62 篇原创文章 · 获赞 118 · 访问量 22万+

猜你喜欢

转载自blog.csdn.net/qq_38412868/article/details/102016832