2020-11-17

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!")

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值