一、time与datetime模块
在Python中,通常有这几种方式来表示时间:
时间戳(timestamp):通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。我们运行“type(time.time())”,返回的是float类型。
格式化的时间字符串(Format String)
结构化的时间(struct_time):struct_time元组共有9个元素共九个元素:(年,月,日,时,分,秒,一年中第几周,一年中第几天,夏令时)
1 import time
2 #--------------------------我们先以当前时间为准,让大家快速认识三种形式的时间
3 print(time.time()) # 时间戳:1487130156.419527
4 print(time.strftime("%Y-%m-%d %X")) #格式化的时间字符串:'2017-02-15 11:40:53'
5
6 print(time.localtime()) #本地时区的struct_time
7 print(time.gmtime()) #UTC时区的struct_time
8 import datetime #可以算出三天前的时间
print(datetime.datetime.now() - datetime.timedelta(days=3)) #可以算出三天前的时间
代码如下:
import time
s = time.localtime()
print(s) #把对应的时间打出来
print(s.tm_year) #取出自己想要的值,年
print(s.tm_mon) #取出自己想要的值,月
res1 =time.localtime(1231331)
res2 = time.strftime('%Y-%m-%d %H:%M:%S',res1) #格式化时间
print(res2)
res1 = time.strptime('2017-11-11 11:11:11',"%Y-%m-%d %H:%M:%S")
res2 = time.mktime(res1)
print(res2) # 转为1510369871.0
二、random模块
import random
print(random.random())#(0,1)----float 大于0且小于1之间的小数
print(random.randint(1,3)) #[1,3] 大于等于1且小于等于3之间的整数
print(random.randrange(1,3)) #[1,3) 大于等于1且小于3之间的整数
print(random.choice([1,'23',[4,5]]))#1或者23或者[4,5]
print(random.sample([1,'23',[4,5]],2))#列表元素任意2个组合
print(random.uniform(1,3))#大于1小于3的小数,如1.927109612082716
模板如下:
item=[1,3,5,7,9]
random.shuffle(item) #打乱item的顺序,相当于"洗牌"
print(item)
随机验证码:(*****)
import random
def make_code(size=4): #默认是4位验证码
res = ''
for k in range(size):
num = str(random.randint(0, 9))
s = chr(random.randint(65, 90))
res += random.choice([num, s])
return res
res = make_code(6) #可以改几位小数
print(res)
三、os模块
import os
1 os.rename() #删除一个文件
2 os.remove('旧文件名','新文件名') #重命名文件/目录
3 os.path.dirname()
4 os.environ #获取系统环境变量
5 os.path.abspath(path) #返回path规范化的绝对路径
6 os.path.split(path) #将path分割成目录和文件名二元组返回
7 os.path.dirname(path) #返回path的目录。其实就是os.path.split(path)的第一个元素
8 res=os.path.join(BASE_DIR,r'db\abb.pc') #拼接文件路径
print(res)
9 os.path.split(path) #将path分割成目录和文件名二元组返回
10 os.path.exists(文件路径) #如果path存在,返回True;如果path不存在,返回False
11 print(os.path.join(BASE_DIR,'logs','access.log')) #拼接文件路径
12 os.path.dirname(path) #返回path的目录。其实就是os.path.split(path)的第一个元素
13 os.path.basename(path) #返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。
四、sys模块
1 sys.argv 命令行参数List,第一个元素是程序本身路径
2 sys.exit(n) 退出程序,正常退出时exit(0)
3 sys.version 获取Python解释程序的版本信息
4 sys.maxint 最大的Int值
5 sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
6 sys.platform 返回操作系统平台名称
代码:
import sys
print(sys.argv)
src_file = input("请输入源文件路径>>>:").strip()
dst_file = input("请输入目标文件路径>>>:").strip()
src_file = sys.argv[1]
dst_file = sys.argv[2]
print(src_file)
print(dst_file)
with open(r'%s' %src_file,mode='rb') as f1,open(r'%s' %dst_file,mode='wb') as f2:
for line in f1:
f2.write(line)
五、shutil模块
打包压缩代码如下:
import shutil #打包
ret =shutil.make_archive('./xxx','gztar',root_dir=r'E:\student\python student\pycharmproject\ATM') #给指定的文件路径进行压缩
import tarfile #找到指定文件夹解压
t =tarfile.open('xxx.tar.gz','r') 打开压缩
t.extractall('./aaa') #找到解压地方
t.close() #关闭
代码2:
import subprocess #当前进行的程序
obj = subprocess.Popen("tasklist", shell=True,
stdout=subprocess.PIPE, #正确执行
stderr=subprocess.PIPE, #错误执行
)
print(obj)
res1 = obj.stdout.read().decode('gbk') #正确执行
res2 = obj.stderr.read().decode('gbk') #错误执行 不是内部或外部命令,也不是可运行的程序
shutil.copyfile(src, dst):拷贝文件
1 shutil.copyfile('f1.log', 'f2.log') #目标文件无需存在
shutil.copymode(src, dst):仅拷贝权限。内容、组、用户均不变
2 shutil.copymode('f1.log', 'f2.log') #目标文件必须存在
六、json与pickle模块
作用:
1、存档---》pickle
2、跨平台交互数据---》json
=====================================>json兼容所有语言,但是不支持所有的python数据类型
====================> dumps--->loads
import json #跟别的语言对接代码
str_json = json.dumps({"x":1,'y':2,'z':True,'a':None})
print(str_json) #结果:{"x": 1, "y": 2, "z": true, "a": null}
dic = json.loads(str_json)
print(dic)
====================> dump--->load
import json
json.dump({"x":1,'y':2,'z':True,'a':None},open('a.json',mode='wt',encoding='utf-8'))
dic = json.load(open('a.json',mode='rt',encoding='utf-8'))
print(dic)