time 模块
time 模块: 与时间相关的模块
时间分为三类:时间戳,结构化,格式化的字符串时间。
1)、时间戳: 从1970-1-01 00:00:00开始到现在的秒数
# -*-coding:utf-8 -*- import time print(time.time()) a = time.time() print(a) 结果: 1540727377.488626 1540727377.488626
2)、结构化: 返回的是一个对象,其中包含一个元组,里面是每个时间的值
(1):localtime
a = time.time() print(a) b = time.localtime(a) print(b) 结果: 1540727966.660054 time.struct_time(tm_year=2018, tm_mon=10, tm_mday=28, tm_hour=19, tm_min=59, tm_sec=26, tm_wday=6, tm_yday=301, tm_isdst=0)
a = time.time() print(a) b = time.localtime(a) print(b.tm_year) #单独获取某个时间——值(属性) 结果: 1540728162.9470487 2018
(2): gmtime 世家统一时间 比北京时间晚8小时。
a = time.time() print(a) l = time.localtime(a) print(l) b = time.gmtime(a) print(b) 结果: 1540728352.4624097 time.struct_time(tm_year=2018, tm_mon=10, tm_mday=28, tm_hour=20, tm_min=5, tm_sec=52, tm_wday=6, tm_yday=301, tm_isdst=0) time.struct_time(tm_year=2018, tm_mon=10, tm_mday=28, tm_hour=12, tm_min=5, tm_sec=52, tm_wday=6, tm_yday=301, tm_isdst=0)
3)、格式化的字符串时间:
(1):strftime
a = time.time() print(a) l = time.localtime(a) b = time.strftime('%Y %m %d',l)
print(b) b1 = time.strftime('%Y %m %d %H:%M:%S',l) print(b1) 结果: 1540729599.7453313
2018 10 28 2018 10 28 20:26:39
# 格式化时间 不能直接对 时间戳进行
a = time.time() print(a) b1 = time.strftime('%Y %m %d %H:%M:%S',a) print(b1) 结果: Traceback (most recent call last): 1540729991.8619258 File "F:/练习/草稿.py", line 12, in <module> b1 = time.strftime('%Y %m %d %H:%M:%S',a) TypeError: Tuple or struct_time argument required
三种格式之间的相互转换:
(1)时间戳转为格式化:
print(time.localtime(a))
(2)结构化转字符串:
a = time.time() b1 = time.localtime(a) b = time.strftime('%Y %m %d %H:%M:%S',b1)
(3)字符串转结构化:
a = time.time() b1 = time.localtime(a) a = time.time() b1 = time.localtime(a) b = time.strftime('%Y %m %d %H:%M:%S',b1) print(b) l = time.strptime(b, '%Y %m %d %H:%M:%S') #---- print(l) 结果: 2018 10 28 20:50:10 time.strtime.asctime(time.localtime())0, tm_mday=28, tm_hour=20, tm_min=50, tm_sec=10, tm_wday=6, tm_yday=301, tm_isdst=-1)
(4):结构化转时间戳
a = time.time() b1 = time.localtime(a) a = time.time() b1 = time.localtime(a) b = time.strftime('%Y %m %d %H:%M:%S',b1) l = time.strptime(b, '%Y %m %d %H:%M:%S') print(l) h = time.mktime(l) print(h) 结果: time.struct_time(tm_year=2018, tm_mon=10, tm_mday=28, tm_hour=20, tm_min=53, tm_sec=21, tm_wday=6, tm_yday=301, tm_isdst=-1) 1540731201.0
总结:
转换方式如下图:
格林威治时间:
print(time.asctime(time.localtime(60*60*24))) print(time.ctime(60*60*24))
结果:
Fri Jan 2 08:00:00 1970
Fri Jan 2 08:00:00 1970
datetime: #这是一个对 时间 进行处理的包
#获取当前详细时间: print(datetime.datetime.now()) 结果 2018-10-28 21:15:31.214708
#获取当前 年 时间: print(datetime.datetime.now().year) 结果: 2018
#替换时间某一属性的值: t = datetime.datetime.now() print(t) t1 = t.replace(year=2020) print(t1) 结果: 2018-10-28 21:19:34.595849 2020-10-28 21:19:34.595849
#时间差——: t = datetime.timedelta(weeks=1) #获取一周时间 print(t) t1 = datetime.datetime.now() #获取当前时间 print(t1) print(t+t1) # 7天后的时间
结果: 7 days, 0:00:00 2018-10-28 21:22:08.941522
2018-11-04 21:22:08.941522