time模块
import time
time.sleep(1) # 休眠多少秒
# 利用时间戳计算耗费时间
start = time.time()
for i in range(10000000):
pass
end = time.time()
print(end - start)
datetime模块
from datetime import datetime
from datetime import date
print(datetime.now())
print(datetime(2018, 1, 2, 12, 12, 13))
print("-------------------------")
t1 = datetime(2018, 1, 2, 12, 30, 13)
t2 = datetime(2018, 1, 4, 12, 40, 13)
diff = t2 - t1
print(diff)
print(diff.total_seconds()) # 一共多少秒
print("-------------------------")
t = datetime.now()
print(t.strftime('%Y年%m月%d日 %H时%M分%S秒'))
print("-------------------------")
t1 = input("输入第一个时间(yyyy-mm-dd HH:MM:SS):")
t2 = input("输入第二个时间(yyyy-mm-dd HH:MM:SS):")
# 把字符串转化成时间
r1 = datetime.strptime(t1, '%Y-%m-%d %H:%M:%S')
r2 = datetime.strptime(t2, '%Y-%m-%d %H:%M:%S')
print(r2 - r1)
print("-------------------------")
print(date.today())
print(date(1988, 12, 3))
random模块
#随机生成验证码
def rand_num():
return str(random.randint(0, 9))
def rand_upper():
return chr(random.randint(65, 90)) # 数字变字母
def rand_lower():
return chr(random.randint(97, 122))
def code(n = 4): # 默认4位
lst = []
for i in range(n):
which = random.randint(1, 3)
if which == 1:
s = rand_num()
elif which == 2:
s = rand_upper()
elif which == 3:
s = rand_lower()
lst.append(s)
return "".join(lst)
print(code())
print(code(5))
pickle模块
import pickle
lst = ['路飞', '黑胡子', '香克斯']
b = pickle.dumps(lst) # 转化成二进制字节
print(b)
lst = pickle.loads(b) # 还原
print(lst)
print("------------------------------")
# 把数据存储到文件中最合理的方法是用pickle
dic = {"name":"路飞", "gender":"男"}
pickle.dump(dic, open("data.txt", mode="wb"))
# 读取序列化后的文件
dic = pickle.load(open("data.txt", mode="rb"))
print(dic)
json模块
import json
# json是一种数据交互的数据模式
# 把python中的字典或列表转化成json字符串
dic = {"id": 1, "name":"路飞", "usertype:": 0}
s = json.dumps(dic, ensure_ascii=False) # json处理中文要加ensure_ascii=False
print(s, type(s))
print("--------------------------------")
# 前端返回的json字符串转化成python中的字典
s = '{"id": 1, "name":"路飞", "usertype:": 0}'
d = json.loads(s)
print(d, type(d))
print("--------------------------------")
# 前端的json和python的字典的区别
d = {"id": 1, "status":True, "islog:": None}
print(json.dumps(d)) # {"id": 1, "status": true, "islog:": null}
print("--------------------------------")
# 列表也可以转化json字符串
lst = ["1", "hh", "你好", True]
s = json.dumps(lst, ensure_ascii=False)
print(s)
print("--------------------------------")
# 读写文件
anime = {
"海贼王": "路飞",
"春物": "大老师",
"age": 20
}
json.dump(anime, open("anime.txt", mode="w", encoding="utf-8"), ensure_ascii=False)
d = json.load(open("anime.txt", mode="r", encoding="utf-8"))
print(d, type(d))
hashlib
import hashlib
# md5是一种不可逆的加密算法,它是可靠的,并且安全的
obj = hashlib.md5() # 创建md5对象
obj.update("看动漫".encode("utf-8")) # 加密信息传递给obj
m = obj.hexdigest() # 拿到密文
print(m)
print("----------------------------------")
# 默认加密过程容易撞库,需要加盐
obj = hashlib.md5(b'asdasd') # 必须是byte类型
obj.update("玩游戏".encode("utf-8"))
print(obj.hexdigest())
shutil
import shutil
shutil.move("dir1/a.txt", "dir2") # 把dir1中的a.txt移动到dir2中
print("------------------------------------")
# 复制文件
f1 = open("dir2/a.txt", mode="rb")
f2 = open("dir1/b.txt", mode="wb")
shutil.copyfileobj(f1, f2)
print("------------------------------------")
# 指定文件路径进行复制,复制的是文件的内容(权限,修改时间等不复制)
shutil.copyfile("dir1/b.txt", "dir1/c.txt")
print("------------------------------------")
#复制文件内容+文件权限
shutil.copy("dir1/b.txt", "dir1/d.txt")
print("------------------------------------")
# 复制文件内容+修改时间
shutil.copy2("xxx.py", "dir1/xxx.py")
print("------------------------------------")
# 复制文件的权限+修改时间,但不复制内容
shutil.copystat("xxx.py", "dir1/xxx.py")
print("------------------------------------")
# 只拷贝文件权限
shutil.copymode("xxx", "dir1/xxx")
print("------------------------------------")
# 复制文件夹,里面的内容也会复制过去
shutil.copytree("dir1", "dir3")
# 删除文件夹
shutil.rmtree("dir3")
logging日志模块
import logging
import os.path
import time
root_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
print(root_path) # 找到主文件夹目录
log_path = os.path.join(root_path, 'log')
class Logger():
def __init__(self):
# 定义日志位置和文件名
self.logname = os.path.join(log_path, "{}.log".format(time.strftime("%Y%m%d")))
# 定义一个日志容器
self.logger = logging.getLogger('log')
# 设置日志打印级别
self.logger.setLevel(logging.DEBUG)
# 设置日志输入的格式
self.formater = logging.Formatter('[%(asctime)s][%(filename)s %(lineno)d][%(levelname)s]: %(message)s')
# 创建日志处理器,存放日志文件
self.filelogger = logging.FileHandler(self.logname, mode='a', encoding='UTF-8')
# 创建日志处理器,在控制台打印
self.console = logging.StreamHandler()
# 设置控制台打印日志界面
self.console.setLevel(logging.DEBUG)
# 文件存放日志级别
self.filelogger.setLevel(logging.DEBUG)
# 文件存放日志格式
self.filelogger.setFormatter(self.formater)
# 控制台打印日志格式
self.console.setFormatter(self.formater)
# 将日志输出渠道添加到日志收集器中
self.logger.addHandler(self.filelogger)
self.logger.addHandler(self.console)
logger = Logger().logger
if __name__ == '__main__':
logger.debug('debug日志')
logger.info('info日志')
logger.warning('warning日志')
logger.error('error日志')