random模块,time模块
random模块
随机小数
print(random.random()) #取0和1之间对小数 print(random.uniform(3,5))#取3到6之间到小数
随机整数
print(random.randint(2,3)) print(random.randrange(2,3)) print(random.randrange(1,10,2))
从列表中随机抽取
print(random.choice(['23',55,654])) print(random.sample([1,4,6,23,5],3))
打乱一个列表到顺序,在原基础的顺序上直接进行修改,节省空间
a=[2,4,6,3,6,8] random.shuffle(a) print(a)
练习: 生成字母数字验证码
def yanzhengma(n=6):
s=''
for i in range(n):
number=str(random.randint(0,9))
alpha=chr(random.randint(65,90))
ALPHA=chr(random.randint(97,122))
choice=random.choice([number,alpha,ALPHA])
s+=choice
return s
print(yanzhengma())
time模块
时间格式
时间戳/浮点型数据类型,以s位单位
print(time.time())
结构化/元组
struct_time=time.localtime()
print(struct_time.tm_mon)
格式化/字符串数据类型
print(time.strftime('%Y-%m-%d %H:%M:%S'))
print(time.strftime('%c'))
时间戳换成字符串时间
a=time.time()
print(a)
b=time.localtime(a)
print(b)
c=time.strftime('%Y-%m-%d %H:%M:%S',b)
print(c)
将字符串转换成分时间戳
a=time.strptime('2018-8-8','%Y-%m-%d')
print(a)
b=time.mktime(a)
print(b)
练习:
1.查看一下2000000000时间戳时间表示的年月日
a=time.localtime(2000000000)
b=time.strftime('%Y-%m-%d %H:%M:%S',a)
print(b)
2.将2008-8-8转换成时间戳时间
a=time.strptime('2008-8-8','%Y-%m-%d')
print(a)
b=time.mktime(a)
print(b)
3.请将当前时间的当前月1号的时间戳时间取出来 - 函数 2018-8-8
def chuo():
a=time.localtime()
b=time.strptime('%s-%s-1' % (a.tm_year,a.tm_mon),'%Y-%m-%d')
c=time.mktime(b)
return c
print(chuo())
4.计算时间差 - 用函数 #2018-8-19 22:10:8 2018-8-20 11:07:3 经过了多少时分秒
import time
def shijiancha(t1,t2):
time1=time.strptime(t1,'%Y-%m-%d %H:%M:%S')
time1=time.mktime(time1)
time2= time.strptime(t2, '%Y-%m-%d %H:%M:%S')
time2 = time.mktime(time2)
time3 =time2-time1
time3=time.gmtime(time3)
print('过去了%s年,%s月,%s天,%s小时,%s分钟,%s秒' % (time3.tm_year-1970,time3.tm_mon-1,time3.tm_mday-1,time3.tm_hour,time3.tm_min,time3.tm_sec))
shijiancha('2018-8-19 22:10:8','2018-8-20 11:07:3')


浙公网安备 33010602011771号