libra-gyf

计算时间差

# 计算时间差的功能
# 如果是年月日,只显示年月
# 2018-9-3 22:48:20
# 2019-9-4 22:48:20
import time
str1 = '2020-2-3 22:48:0'
str2 = '2019-9-4 22:48:20'
struct_time1 = time.strptime(str1, "%Y-%m-%d %H:%M:%S")
stamp1 = time.mktime(struct_time1)
struct_time2 = time.strptime(str2, "%Y-%m-%d %H:%M:%S")
stamp2 = time.mktime(struct_time2)
t = stamp1-stamp2
ret = time.gmtime(t)
print('{}年 {}月 {}日 {}小时 {}分钟 {}秒' .format (ret.tm_year-1970,
                             ret.tm_mon-1,
                             ret.tm_mday-1,
                             ret.tm_hour,
                             ret.tm_min,
                             ret.tm_sec))
import time
str1 = '2020-2-3 22:48:0'
str2 = '2019-9-4 22:48:20'


def time_diff(time_start, time_end, fmt="%Y-%m-%d %H:%M:%S"):
    def stamp_func(t): return time.mktime(time.strptime(t, fmt))
    stamp1 = stamp_func(time_end)
    stamp2 = stamp_func(time_start)
    t = abs(stamp1-stamp2)
    ret = time.gmtime(t)
    return (ret.tm_year-1970,
            ret.tm_mon-1,
            ret.tm_mday-1,
            ret.tm_hour,
            ret.tm_min,
            ret.tm_sec)


ret = time_diff(str2, str1)
print(ret)

 

posted on 2020-02-05 17:00  libra-gyf  阅读(104)  评论(0编辑  收藏  举报

导航