首页 > 代码库 > python学习(day5)
python学习(day5)
9、时间模块:
import time print(time.clock()) #返回处理器时间,3.3开始已废弃 , 改成了time.process_time()测量处理器运算时间,不包括sleep时间,不稳定,mac上测不出来 print(time.altzone/3600) #返回与utc时间的时间差,以秒计算print(time.asctime()) #返回时间格式"Fri Aug 19 11:14:16 2016", t = time.localtime() t2 = time.localtime(time.time()+3600*3)#时间运算,当前时间加3个小时 print(t) print(t2) print(time.localtime()) #返回本地时间 的struct time对象格式 # print(time.gmtime(time.time()-800000)) #返回utc时间的struc时间对象格式 print(t.tm_year,t.tm_mday) print(time.time())#时间戳,1970年开始到现在的时间 print(time.time()/(3600*24*365)) print(time.gmtime())#utc时间 print(time.asctime(time.localtime())) #返回时间格式"Fri Aug 19 11:14:16 2016", print(time.ctime()) #返回Fri Aug 19 12:38:29 2016 格式, 同上 #日期字符串 转成 时间戳 string_2_struct = time.strptime("2016/05/22","%Y/%m/%d") #将 日期字符串 转成 struct时间对象格式 string_3_struct = time.strptime("2016-05-22 23:30:30","%Y-%m-%d %H:%M:%S") #将 日期字符串 转成 struct时间对象格式 print(string_2_struct) print(string_3_struct) # struct_2_stamp = time.mktime(string_2_struct) #将struct时间对象转成时间戳 struct_3_stamp = time.mktime(string_3_struct) #将struct时间对象转成时间戳 print(struct_2_stamp) print("struct_3_stamp",struct_3_stamp) #将时间戳转为字符串格式 print(time.gmtime(time.time()-86640)) #将utc时间戳转换成struct_time格式 print(time.localtime(time.time()-86640)) #将local时间戳转换成struct_time格式 print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将utc struct_time格式转成指定的字符串格式 t2 = time.strptime("2016-11-11 23:30:30","%Y-%m-%d %H:%M:%S")#字符串转struct时间对象格式 print("时间对象t2",t2) t3 = time.mktime(t2)#将struct时间对象转成时间戳 print("时间戳t3",t3) #t3_str1 = time.strftime("%Y %m %d %H:%M:%S",t3)#时间戳转字符串 print("时间戳转字符串",time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime())) #时间加减 import datetime print("datetime".center(50,‘-‘)) print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925print(datetime.date.fromtimestamp(time.time()) ) # 时间戳直接转成日期格式 2016-08-19 print(datetime.datetime.now() ) print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天 print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天 print(datetime.datetime.now() - datetime.timedelta(3)) #当前时间-3天 print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时 print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分 c_time = datetime.datetime.now() print(c_time.replace(minute=23,hour=23,month=5,day=1,year=2020)) #时间替换
10、Random模块:
import random,string print(random.random())#随机生成的一个实数,它在[0,1)范围内 print(random.randint(1,2))#随机生成整数n,1<=n<=2 print(random.randrange(1,2))#随机生成整数n,1<=n<2 print(random.sample(‘qweasdasf‘,3))#random.sample(sequence, k),从指定序列中随机获取指定长度的片断。sample函数不会修改原有序列 list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] slice = random.sample(list, 5) #从list中随机获取5个元素,作为一个片断返回 print(slice) print(list) #原有序列并没有改变。 print(string.ascii_letters) print(string.digits) str = string.ascii_letters+string.digits print(‘‘.join(random.sample(str,6)))#随机取6位 #生成随机验证码: checkcode = ‘‘ for i in range(4): current = random.randrange(0,4) if current != i: temp = chr(random.randint(65,90)) else: temp = random.randint(0,9) checkcode += ‘%s‘%temp print(checkcode)
11、Shutil模块:
import shutil #http://www.cnblogs.com/wupeiqi/articles/4963027.html # f1 = open("time_module.py") # f2 = open("time_module_new.py","w") # shutil.copyfileobj(f1,f2)#将文件内容拷贝到另一个文件中,可以部分内容 #shutil.copy(r"C:\Users\Administrator\PycharmProjects\s14\day1\userdata.txt","test_copy")#拷贝文件和权限,复制一个文件到一个文件或一个目录,r是保持字符串原始值的意思,就是说不对其中的符号进行转义 #shutil.copy2()#在copy上的基础上再复制文件最后访问时间与修改时间也复制过来了,类似于cp –p的东西 #shutil.copyfile()#拷贝文件,copyfile( src, dst)从源src复制到dst中去。当然前提是目标地址是具备可写权限。抛出的异常信息为IOException. 如果当前的dst已存在的话就会被覆盖掉 # shutil.copytree(r"C:\Users\Administrator\PycharmProjects\s14\day4","day4_new")#copytree(olddir,newdir,True/Flase),把olddir拷贝一份newdir,如果第3个参数是True,则复制目录时将保持文件夹下的符号连接,如果第3个参数是False,则将在复制的目录下生成物理副本来替代符号连接 # # shutil.rmtree()#递归的去删除文件 # shutil.move(src, dst)#递归的去移动文件 #shutil.make_archive(‘base_name‘, format,...)#创建压缩包并返回文件路径,例如:zip、tar # shutil.make_archive(r"C:\day4_copy", format="zip",root_dir=r"C:\Users\Administrator\PycharmProjects\s14\day4") #压缩解压: import zipfile # zip_obj = zipfile.ZipFile(r"C:\day4_copy.zip","a")#‘r‘表示打开一个存在的只读ZIP文件;‘w‘表示清空并打开一个只写的ZIP文件,或创建一个只写的ZIP文件;‘a‘表示打开一个ZIP文件,并添加内容。 # zip_obj.write("test_copy")#将test_copy文件写进压缩文件 # zip_obj.close() # z = zipfile.ZipFile("C:\day5_copy.zip","r")#解压zip文档中的所有文件到当前目录 # z.extractall() # z.close() # import tarfile#把工作空间下面的所有文件,打包生成一个tar文件,同时提供一个方法把该tar文件中的一些文件解压缩到指定的目录中 # tar = tarfile.open(r"C:\daytest_copy.zip","w") # tar.add(r"C:\Users\Administrator\PycharmProjects\s14\day4",arcname="tetsname") # tar.add(r"C:\day5_copy.zip")
12、Json and pickle序列化:
#Json 序列化 import json info = { "name":"jack", "age":23 } f = open("test.text","w") #print(type(json.dumps(info)),json.dumps(info)) f.write(json.dumps(info))#json.dumps将 Python 对象编码成 JSON 字符串 f.close()
#Json 反序列化 import json#支持所有语言,python,Java等,但json只能针对简单的python对象如字典,列表等。函数则不可以(pickle可以) f = open("test.text","r") data = json.loads(f.read())#json.loads 将已编码的 JSON 字符串解码为 Python 对象 print(data["age"])
#import json import pickle def sayhi(name): print("hello:",name) info = { "name":"jack", "age":23, "func":sayhi } f = open("test.text","wb") #print(type(json.dumps(info)),json.dumps(info)) #f.write(pickle.dumps(info))#json.dumps将 Python 对象编码成 JSON 字符串 pickle.dump(info,f)#等同于f.write(pickle.dumps(info)) f.close()
import pickle#pickle#pickle针对所有python对象,但仅限于python,java等不认识pickle def sayhi(name): print("hello:",name) f = open("test.text","rb") #data = pickle.loads(f.read())#json.loads 将已编码的 JSON 字符串解码为 Python 对象 data = pickle.load(f)#等同于data = pickle.loads(f.read()) print(data["func"]) print(data["func"]("jack"))
import json info = { "name":"jack", "age":23 } f = open("test.text","w") #print(type(json.dumps(info)),json.dumps(info)) f.write(json.dumps(info))#json.dumps将 Python 对象编码成 JSON 字符串 info["age"]=21 f.write(json.dumps(info)) f.close()
import json f = open("test.text","r") #data = pickle.loads(f.read())#json.loads 将已编码的 JSON 字符串解码为 Python 对象 data = json.load(f)#等同于data = pickle.loads(f.read()) print(data) #注:dump多次,load报错。尽量dump一次,load一次
import pickle#pickle针对所有python对象,但仅限于python,java等不认识pickle def sayhi(name): print("hello:",name) info = { "name":"jack", "age":23, "func":sayhi } f = open("test.text","wb") #print(type(json.dumps(info)),json.dumps(info)) f.write(pickle.dumps(info))#json.dumps将 Python 对象编码成 JSON 字符串 f.close()
import pickle#pickle#pickle针对所有python对象,但仅限于python,java等不认识pickle def sayhi(name): print("hello:",name) f = open("test.text","rb") data = pickle.loads(f.read())#json.loads 将已编码的 JSON 字符串解码为 Python 对象 print(data["func"]) print(data["func"]("jack"))
13、XML处理:
import xml.etree.ElementTree as ET #创建xml文档 new_xml = ET.Element("namelist")#根节点 name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"})#子节点 age = ET.SubElement(name,"age",attrib={"checked":"no"}) sex = ET.SubElement(name,"sex") sex.text = ‘33‘ name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"}) age = ET.SubElement(name2,"age") age.text = ‘19‘ et = ET.ElementTree(new_xml) #生成文档对象 et.write("test_new.xml", encoding="utf-8",xml_declaration=True) ET.dump(new_xml) #打印生成的格式
import xml.etree.ElementTree as ET tree = ET.parse("test.xml")#解析文件 root = tree.getroot()#获取到根节点 print(root.tag)#打印根节点标签 #遍历xml文档 for child in root: print(child.tag, child.attrib)#child.attrib节点属性 for i in child: print(i.tag,i.attrib,i.text)#i.text节点文本 #只遍历year 节点 for node in root.iter(‘year‘): print(node.tag,node.text) #修改 for node in root.iter(‘year‘): new_year = int(node.text) + 1 node.text = str(new_year) node.set("updated","yes")#更新属性 tree.write("xmltest.xml") #删除node for country in root.findall(‘country‘): rank = int(country.find(‘rank‘).text) if rank > 50: root.remove(country) tree.write(‘output.xml‘)
14、configparser模块:
import configparser config = configparser.ConfigParser() config["DEFAULT"] = {‘ServerAliveInterval‘: ‘45‘, ‘Compression‘: ‘yes‘, ‘CompressionLevel‘: ‘9‘} config[‘bitbucket.org‘] = {} config[‘bitbucket.org‘][‘User‘] = ‘hg‘ config[‘topsecret.server.com‘] = {} topsecret = config[‘topsecret.server.com‘] topsecret[‘Host Port‘] = ‘50022‘ # mutates the parser topsecret[‘ForwardX11‘] = ‘no‘ # same here config[‘DEFAULT‘][‘ForwardX11‘] = ‘yes‘ with open(‘example.ini‘, ‘w‘) as configfile: config.write(configfile)
import configparser config = configparser.ConfigParser() config.read("example.ini") print(config.sections()) #读: section_name = config.sections()[1] print(config[section_name]["host port"]) #print(config.options(section_name)) #print(config.items(section_name)) #print("2312:",config.get(‘bitbucket.org‘,‘user‘)) for i,v in config[section_name].items(): print(i,v) #删除: config.remove_option(section_name,"forwardx11") config.write(open("example_new","w")) #修改: config.set(section_name,"host port","3000") config.write(open("example_new","w"))
15、hashlib模块:
import hashlib m = hashlib.md5() m.update(b"jack") print(m.hexdigest()) m.update(b"rose") print(m.hexdigest()) m2 = hashlib.md5() m2.update(b"jackrose") print(m2.hexdigest()) hash2 = hashlib.sha256() hash2.update(b"jackrose") print(hash2.hexdigest()) hash3 = hashlib.sha512() hash3.update(b"jackrose") print(hash3.hexdigest()) import hmac #hmac 模块,它内部对我们创建 key 和 内容 再进行处理然后再加密 h = hmac.new(b"jack", b"rose") print(h.hexdigest())
16、logging模块:
import logging logging.basicConfig(filename=‘example.log‘,level=logging.INFO, format=‘%(asctime)s %(filename)s %(lineno)d - %(levelname) s%(message)s‘, datefmt=‘%m/%d/%Y %I:%M:%S %p‘)#日志写到文件 #level=loggin.INFO,把日志纪录级别设置为INFO,也就是说,只有比日志是INFO或比INFO级别更高的日志才会被纪录到文件 #format=‘%(asctime)s %(message)s‘, datefmt=‘%m/%d/%Y %I:%M:%S %p‘,日志格式加上时间 #livel级别:debug<info<error<warning<critical logging.warning("user [alex] attempted wrong password more than 3 times") logging.critical("server is down") logging.info("test info") logging.debug("test debug") logging.error("test error")
#多输出: import logging #create logger logger = logging.getLogger(‘TEST-LOG‘) logger.setLevel(logging.DEBUG) # create console handler and set level to debug ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create file handler and set level to warning fh = logging.FileHandler("access.log") fh.setLevel(logging.WARNING) # create formatter formatter = logging.Formatter(‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘) # add formatter to ch and fh ch.setFormatter(formatter) fh.setFormatter(formatter) # add ch and fh to logger logger.addHandler(ch) logger.addHandler(fh) # ‘application‘ code logger.debug(‘debug message‘) logger.info(‘info message‘) logger.warn(‘warn message‘) logger.error(‘error message‘) logger.critical(‘critical message‘)
#文件自动截断: import logging from logging import handlers logger = logging.getLogger("timelog.log") log_file = "timelog.log" # fh = handlers.RotatingFileHandler(filename=log_file,maxBytes=10,backupCount=3,encoding="utf-8") fh = handlers.TimedRotatingFileHandler(filename=log_file,when="S",interval=5,backupCount=3,encoding="utf-8") formatter = logging.Formatter(‘%(asctime)s %(module)s:%(lineno)d %(message)s‘) fh.setFormatter(formatter) logger.addHandler(fh) import time time.sleep(2) logger.warning("test1") time.sleep(2) logger.warning("test12") time.sleep(2) logger.warning("test13") logger.warning("test14")
17、re正则表达式:
见:http://www.cnblogs.com/alex3714/articles/5161349.html
python学习(day5)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。