模块的分类
(1)标准库(内置模块)
python自带的模块,例如:time,datetime
python中常用的时间的表示方式:格式化后的字符串,时间戳,元组
#Author:Anliu import time,datetime print(time.time()) #获取时间戳 print(time.localtime()) #本地时间 UTC+8,元组的形式呈现 time.sleep(2) #程序停2秒 print(time.gmtime()) #UTC时间,元组的形式呈现 print(time.gmtime(time.time())) x=time.gmtime() print(x) print(x.tm_year) print(x.tm_mon) print(x.tm_mday) print(time.mktime(x)) #元组转化为时间戳 print(time.strftime("%Y-%m-%d %H:%M:%S",x)) #元组转化为格式化的字符串 print(time.strptime("2019-11-08 01:52:03","%Y-%m-%d %H:%M:%S")) #格式化的字符串转化成元组 print(time.asctime()) #元组转换成字符串格式 print(time.ctime()) #时间戳转换成字符串格式 print(datetime.datetime.now()) #打印当前时间 print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间的后3天 print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间的前3天 print(datetime.datetime.now() + datetime.timedelta(hours=8)) print(datetime.datetime.now() + datetime.timedelta(hours=-8))
random模块
#Author:Anliu import random print(random.random()) #随机浮点数 print(random.randint(1,3)) #打印1,3的随机整数 print(random.randrange(1,3)) #打印1,2的随机整数 print(random.choice('hello')) #字符串列表或者元素 print(random.sample('hello',2)) #随机取两个字符 list=["a","b","c","d","e","f","g"] random.shuffle(list) #打乱列表顺序 print(list)
random实例:验证码
#Author:Anliu import random #打印四位数字 #checkcode='' #for i in range(4): # current=random.randint(1,9) # checkcode+=str(current) #print(checkcode) #打印四位数字加字母 checkcode='' for i in range(4): current=random.randrange(0,4) if current == i: tmp = chr(random.randint(65,90)) else: tmp = random.randint(0,9) checkcode+=str(tmp) print(checkcode)
(2)开源模块
(3)自定义模块