time模块:
时间戳(电脑)、格式化字符串(人)、时间元组(计算)
import time
print(time.time()) # 1536500505.9982672 时间戳
print(time.strftime('%Y-%m-%d %H:%M:%S')) # 2018-09-09 21:50:16
s = time.localtime() # 结构化时间
# time.struct_time(tm_year=2018, tm_mon=9, tm_mday=9, tm_hour=21, tm_min=52, tm_sec=23, tm_wday=6, tm_yday=252, tm_isdst=0)
print(s)
print(s.tm_year) # 2018
时间转换:通过结构化时间转换
时间戳转换成结构化时间:
import time
# 时间戳和结构化时间转换
t = time.time()
# 北京时间localtime
# time.struct_time(tm_year=2018, tm_mon=9, tm_mday=9, tm_hour=21, tm_min=55, tm_sec=28, tm_wday=6, tm_yday=252, tm_isdst=0)
print(time.localtime(t))
# 格林威治时间gmtime
# time.struct_time(tm_year=2018, tm_mon=9, tm_mday=9, tm_hour=13, tm_min=55, tm_sec=28, tm_wday=6, tm_yday=252, tm_isdst=0)
print(time.gmtime(t))
结构化时间转换成时间戳:
import time
t = time.localtime()
print(time.mktime(t)) # 1536501555.0
字符串时间转换成结构化时间:
import time
# time.struct_time(tm_year=2000, tm_mon=12, tm_mday=31, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=366, tm_isdst=-1)
print(time.strptime('2000-12-31', '%Y-%m-%d'))
结构化时间转换成字符串时间:
import time
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())) # 2018-09-09 22:04:11
字符串时间差计算:先转换成时间戳计算,然后转换成结构化时间
import time
t1 = '2018-09-09 12:00:01'
t2 = '2018-09-06 10:01:20'
# 字符串时间转换成结构化时间
t3 = time.strptime(t1, '%Y-%m-%d %H:%M:%S')
t4 = time.strptime(t2, '%Y-%m-%d %H:%M:%S')
# 结构化时间转换成时间戳
t5 = time.mktime(t3)
t6 = time.mktime(t4)
# 计算
t = t5 -t6
# 时间戳转换成结构化时间,需要用格林威治时间
struct_time = time.gmtime(t) # time.struct_time(tm_year=1970, tm_mon=1, tm_mday=4, tm_hour=1, tm_min=58, tm_sec=41, tm_wday=6, tm_yday=4, tm_isdst=0)
# 过去了0年0月3天1小时58分钟41秒
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))