一 time模块(时间模块)★★★★
时间表现形式
在Python中,通常有这三种方式来表示时间:时间戳、元组(struct_time)、格式化的时间字符串:
(1)时间戳(timestamp) :通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。我们运行“type(time.time())”,返回的是float类型。
(2)格式化的时间字符串(Format String): ‘1988-03-16’
(3)元组(struct_time) :struct_time元组共有9个元素共九个元素:(年,月,日,时,分,秒,一年中第几周,一年中第几天等)
import time res=type(time.time()) #我们运行“type(time.time())”,返回的是float类型 print(res) #打印结果 <class 'float'> 时间戳 import time print(time.time()) #返回当前时间的时间戳 从1970年到现在时间的总秒数 #打印结果 1493204066.464622 时间字符串 import time res=time.strftime("%Y-%m-%d %X") #返回当前时间,按年-月-日 时分秒显示,中间的连接符自定义 print(res) #打印结果 2017-04-26 18:54:48 时间元组 import time res=time.localtime() #返回 年,月,日,时,分,秒,一年中第几周,一年中第几天,夏令时 print(res) 打印结果 time.struct_time(tm_year=2017, tm_mon=4, tm_mday=26, tm_hour=18, tm_min=55, tm_sec=7, tm_wday=2, tm_yday=116, tm_isdst=0)
小结:时间戳是计算机能够识别的时间;时间字符串是人能够看懂的时间;元组则是用来操作时间的
几种时间形式的转换
⑴
式的转换 #1,时间戳<---->结构化时间: localtime/gmtime mktime import time a1=time.localtime(3600*24) a2=time.gmtime(3600*24) print(a1) print(a2) a3=time.mktime(time.localtime()) print(a3) #2,字符串时间<---->结构化时间: strftime/strptime import time a1=time.strftime("%Y-%m-%d %X", time.localtime()) a2=time.strptime("2017-03-16","%Y-%m-%d") print(a1) print(a2
⑵
>>> time.asctime(time.localtime(312343423)) 'Sun Nov 25 10:03:43 1979' >>> time.ctime(312343423) 'Sun Nov 25 10:03:43 1979'
1 #--------------------------其他方法 2 # sleep(secs) 3 # 线程推迟指定的时间运行,单位为秒。
二 random模块(随机数模块)★★
1 >>> import random 2 >>> random.random() # 大于0且小于1之间的小数 3 0.7664338663654585 4 5 >>> random.randint(1,5) # 大于等于1且小于等于5之间的整数 6 7 >>> random.randrange(1,3) # 大于等于1且小于3之间的整数 8 9 >>> random.choice([1,'23',[4,5]]) # #1或者23或者[4,5] 10 11 >>> random.sample([1,'23',[4,5]],2) # #列表元素任意2个组合 12 [[4, 5], '23'] 13 14 >>> random.uniform(1,3) #大于1小于3的小数 15 1.6270147180533838 16 17 >>> item=[1,3,5,7,9] 18 >>> random.shuffle(item) # 打乱次序 19 >>> item 20 [5, 1, 3, 7, 9] 21 >>> random.shuffle(item) 22 >>> item 23 [5, 9, 7, 1, 3]
1 import random 2 3 def v_code(): 4 5 code = '' 6 for i in range(5): 7 8 num=random.randint(0,9) 9 alf=chr(random.randint(65,90)) 10 add=random.choice([num,alf]) 11 code="".join([code,str(add)]) 12 13 return code 14 15 print(v_code())