内置模块(标准库)----时间模块 &random模块

一。时间模块(※※※※)

import time
#时间戳(用途,计算运行了多少时间)
print(time.time())          #输出1587996158.5779295,代表一个秒数,从1970.1.1到现在有多少秒

#
结构化时间 print(time.localtime()) #输出结果time.struct_time(tm_year=2020, tm_mon=4, tm_mday=27, tm_hour=22, tm_min=6, tm_sec=7, tm_wday=0, tm_yday=118, tm_isdst=0) #这周的第几天 t=time.localtime() print(t.tm_year) #输出今年的年份 print(t.tm_wday) #输出今天是这周的第几天

print(time.gmtime()) #utc 输出世界标准时间 #输出结果为time.struct_time(tm_year=2020, tm_mon=4, tm_mday=27, tm_hour=14, tm_min=10, tm_sec=26, tm_wday=0, tm_yday=118, tm_isdst=0)

#------将结构化时间转化为时间戳的方法
print(time.mktime(time.localtime()))
 
 
#一.结构化时间和标准字符串时间的相互转化
#结构化时间----》字符串时间
print(time.strftime("%Y-%m-%d %X",time.localtime())) #输出结果2020-04-27 22:25:46 注意%后面的写法
#字符串时间----》结构化时间
print(time.strptime("2020-4-27 22:27:45","%Y-%m-%d %X")) #前面是一个自己定义的字符串时间,中间的分割符号怎么写都行。后面用%表示与前面对应相
#输出结果为 time.struct_time(tm_year=2020, tm_mon=4, tm_mday=27, tm_hour=22, tm_min=27, tm_sec=45, tm_wday=0, tm_yday=118, tm_isdst=-1)
 
 
print(time.asctime())      #直观的输出时间Mon Apr 27 22:32:06 2020
 
import datetime
print(datetime.datetime.now())
#输出结果为2020-04-27 22:36:33.612706

二.内置的random模块

import  random
ret=random.random()             #输出的是0-1的浮点数
print(ret)
res=random.randint(1,94)          #输出的是[1,94]之间随机的整数
print(res)
rer=random.randrange(1,94)      #输出的是[1,94)之间随机的整数
print(rer)
yxz=random.choice([1,2,33,44])    #对列表中的元素随机选取,每个的概率都为25%
print(yxz)
ymz=random.sample([1,2,33,44,55],2)    #列表中的值随机选取两个,后面的2代表选几个值
print(ymz)
yy=random.uniform(1,3)     #输出的是任意范围内的浮点型的数
print(yy)


#随机生成验证码的函数
import random
def v_code():
    ret=""
    for i in range(5):
        num=random.randint(0,9)
        alf=chr(random.randint(65,122))     #通过chr将对应数字转换成ascii码,65-122是大写A到小写z的范围
        shengcheng=str(random.choice([num,alf]))     #注意这里一定要转换成字符串的形式
        ret+=shengcheng
    return ret
print(v_code())

猜你喜欢

转载自www.cnblogs.com/yxzymz/p/12790755.html