python 模块
时间模块
import time
1.时间戳 1970-01-01 00:00:00 (格林威治时间0时区) 秒数
print(time.time())
优点:存储方便,占有空间小,方便计算操作
缺点:不方便查看时间
2.时间元组
print(time.localtime())
优点:方便程序调用
缺点:没有格式
3.格式化时间字符串(需要时间的格式)
print(time.strftime("%d/%m/%Y %H:%M:%S"))
1.将时间戳-> 时间元组
gmtime -> utc 国际标准时间
localtime -> 本地时间
72047023 print(time.gmtime(72047023)) print(time.localtime(72047023))
2.将时间元组转为时间字符串
print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime(0)))
print(time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(0)))
3.将时间字符串转为时间元组
print(time.strptime(“2200-11-11 12:30:29”,"%Y-%m-%d %H:%M:%S"))
4.将时间元组转为时间戳
print(time.mktime(time.strptime(“2200-11-11 12:30:29”,"%Y-%m-%d
%H:%M:%S")))
时间戳 <-> 时间元组 <-> 时间字符串
import datetime
datetime是time模块的一个封装 print(datetime.datetime.now())
json 模块
json 原本是JavaScript中的一种数据格式,类似于Python中的字典
Python中的对象 -> JSON格式的字符串 (序列化)
JSON格式的字符串 -> Python中的数据对象 (反序列化操作)
dump 导出操作 python对象-> json字符串
load 导入操作 json字符串-> python对象
import json
> dic = { 'name':'zj',
> 'age':18, 'tup':('a',1,2,3,4,True,False), }
>
> json.dumps(obj) 字符串导出 json.dump(obj,f) 文件写入 with
> open("data.json","w",encoding="utf-8") as f: json.dump(dic,f)
>
> data = json.loads('{"pi":3.141592653}') print(data["pi"]*3)
> json.loads(字符串) -> python对象 json.load(文件对象) -> python对象 with
> open("data.json","r",encoding="utf-8") as f: data = json.load(f)
> print(data["name"])
# 随机数
随机一个整数randint() 包含开头结尾
print(random.randint(1,43))
随即一个小数random() 0~1
print(random.random())
随机一个范围randrange(开始值,结束值,步长值) 含头不含尾0-9
print(random.randrange(0,10,2))
choice() 随机一个元素
print(random.choice(’“a1”,“b2”,“c3”,“d4”’))
- 数字6位验证码
print(random.randint(1000,9999)) - n位随机数字+大写字母
- 数字与字母都随机
- 字母数字位置也随机
def verification_code(n):
code = ""
for i in range(n):
num = random.randint(0,9)
if i % 2 == 0:
code += chr(random.randint(65,90))
else:
code += str(random.randint(0,9))
return code
print(verification_code(8))