Python笔记
Python random模块(获取随机数)常用方法和使用例子
random作为Python自带的模块,无需下载即可直接使用。import random导入该模块。
•random
random.random() 会生成一个[0,1)之间的随机小数。
•uniform
random.uniform(a,b) 指定范围内的随机浮点数
import random
print(random.uniform(10,20)) #18.324867
•randint
random.randint(start,end) 随机一个整数,包含开始值和结束值。
import random
print(random.randint(1000,9999)) #四位纯数字验证码
•randrange
random.randrange(0,11,2) 2表示步长值 不含11 #随机选取0到10间的偶数
随机范围:前闭后开(包含开始值,不包含结束值)
•choice
random.choice()随机序列中的某个值
print(random.choice(["a","1","b","2","c"]) 参数表示一个有序类型,list,tuple,字符串
•shuffle
random.shuffle() 用于将一个列表中的元素打乱
import random
items = [1,2,3,4,5]
print(random.shuffle(items)) #[3,5,4,1,2]
大写字母+数字的n位验证码:
import random
def verification_code(n): #verification_code验证码
code=""
for i in range(n):
num = random,randint(0,9)
if num % 2 == 0:
code += str(random.randint(0,9))
else:
code += chr(random.randint(65,90)) #65-90对应的字母
return code
print(verification_code(4)) #随机的四位包含数字和字母的验证码
time时间模块
import time 导入时间模块
时间戳(小数) 1970-01-01 00:00:00(格林威治时间)
import time
#print(time.time()) #直接获取当前时间戳
print(1970+time.time()/60/60/24/365) #获取当前年份 2020.9……
功能:方便计算机存储,方便运算
时间元组(命名元组类型) 中间时态 作为函数的参数,开发时使用
print(time.localtime())
格式化时间字符串
import time
print(time.strftime("%Y-%m-%d" "%H:%M:%S"))
#Y:年 m:月 d:日 H:小时 M:分 S:秒
时间戳—>时间元组—>时间字符串
import time
print(time.localtime(54378346)) #转换成时间元组
print(time.strftime("%Y-%m-%d" "%H:%M:%S",time.localtime(54378346))) #转换成时间字符串
时间字符串—>时间元组—>时间戳
import time
print(time.strptime("2001-9-11 8:30:00","%Y-%m-%d" "%H:%M:%S")) #转换成时间元组
print(time.mktime(time.strptime("2001-9-11 8:30:00","%Y-%m-%d" "%H:%M:%S"))) #转换成时间戳
睡眠:
import time
time.sleep(3) #3秒
print("hello world!")