Python常用模块系列
1.时间模块
import time,datetime # print(time.time()) #时间戳
# print(time.strftime("%Y-%m-%d %X")) #格式化时间
# print(time.localtime()) #本地的struct_time
# print(time.gmtime()) #本地的utc时间
# print(time.ctime()) #英文日期 #时间加减
print(datetime.datetime.now()) #显示当前时间的毫秒
print(datetime.date.fromtimestamp(time.time())) #将时间戳直接转成日期格式
print(datetime.datetime.now() + datetime.timedelta(3)) #显示现在时间加三天
print(datetime.datetime.now() + datetime.timedelta(-3)) #显示现在时间减三天
print(datetime.date.fromtimestamp(time.time()) + datetime.timedelta(3)) #当前时间取整加三
print(datetime.date.fromtimestamp(time.time()) + datetime.timedelta(-3)) #当前时间取整减三
print(datetime.datetime.now() + datetime.timedelta(hours=3))#显示现在时间加三小时
print(datetime.datetime.now() - datetime.timedelta(hours=3))#显示现在时间减三小时
print(datetime.datetime.now() + datetime.timedelta(minutes=30))#显示现在时间加三十分
#时间替换
now_time = datetime.datetime.now()
print(now_time.replace(minute=3,hour=2))
- 其中计算机认识的时间只能是'时间戳'格式,而程序员可处理的或者说人类能看懂的时间有: '格式化的时间字符串','结构化的时间' ,于是有了下图的转换关系
2.random模块
import random # print(random.random()) #随机生成一个大于0到小于1的小数 (0,1)
# print(random.randint(1,3)) #随机生成一个大于等于1小于等于三的整数 [1,3] #打乱列表顺序
# item=[1,2,3,4,5,6]
# random.shuffle(item)
# print(item) #生成几位随机验证码
def range_code(n):
res=''
for i in range(n):
s1=chr(random.randint(65,90))
s2=str(random.randint(0,9))
res+=random.choice([s1,s2])
return res print(range_code(6))
3.logging模块
'''
日志级别:
critical(严重)=50
error(错误)=40
warning(警告)=30
info(正常)=20
debug(调试级别)=10
notset(没有设置日志级别)=0
默认用root产生日志
控制日志打印到文件中,并且自己定制日志的输出格式
''''' # import logging #默认是warning
#
# logging.basicConfig(
# filename="access.log",
# format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
# datefmt="%Y-%m-%d %H:%M:%S",
# level=10,
# )
# logging.debug("debug:debug log")
# logging.info("info:info log")
# logging.warning("warning: warning log")
# logging.error("error: error log")
# logging.critical("critical: critical log") import logging #产生对象
logger=logging.getLogger("root")
#产生日志
# logger.debug("debug")
# logger.info("info:info log")
# logger.warning("warning: warning log")
# logger.error("error: error log")
# logger.critical("critical: critical log")
#filter对象,过滤,省略
#handler对象,负责接收logger对象传来的日志内容,控制打印到哪里,
h1=logging.FileHandler("t1.log")
h2=logging.FileHandler("t2.log")
h3=logging.StreamHandler()
#定制日志格式
#给文件
formatter1=logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt="%Y-%m-%d %H:%M:%S",
)
#给终端
formatter2=logging.Formatter(
'%(asctime)s - %(message)s',
datefmt="%Y-%m-%d %H:%M:%S",
) #建立关系:logger对象才能把自己的日志交给handle负责输出
logger.addHandler(h1)
logger.addHandler(h2)
logger.addHandler(h3)
logger.setLevel(10) #绑定日志格式到Filehandler(文件)对象
h1.setFormatter(formatter1)
h2.setFormatter(formatter1)
#绑定日志格式到StreamHandler(终端)对象
h3.setFormatter(formatter2) #设置日志级别
h1.setLevel(10)
h2.setLevel(10)
h3.setLevel(30) logger.debug("debug")
logger.info("info")
logger.warning("warning")
# logger.error("error")
# logger.critical("critical")
4.re模块
4.1 匹配模式
import re
# print(re.findall('asd',"asd asd ads asdasd 1#¥%das")) #匹配到了4个
# print(re.findall('aaa',"aaaa")) #只匹配到1个
'''
\w 匹配字数数字下滑线
\W 不匹配字母数字下滑线
'''
# print(re.findall("\w","hello world 123_456 $%"))
# print(re.findall("\W","hello world 123_456 $%"))
# print(re.findall("\s","hello world 123_456 $%"))
# print(re.findall("\S","hello world 123_456 $%"))
# print(re.findall("\d\d","hello world 123_456 $%"))
# print(re.findall("^h","hello world 123_456 $%"))
# print(re.findall("\$$","hello world 123_456 $%$"))
# print(re.findall("a.c","abc asc a&c a\nc a c"))
# print(re.findall("a.c","abc asc a&c a\nc a c",re.S)) #re.S可以匹配到换行 '''
. 任意
* 出现0次以上
+ 至少出现一次
? 出现0次或1次
.* 贪婪匹配
.*? 非贪婪匹配
'''
5. json模块
import json
user={"name":"xiaojin","pwd":123}
with open("db.txt","w",encoding="utf-8") as write_f:
line=json.dumps(user)
write_f.write(line) with open("db.txt","r",encoding="utf-8") as read_f:
data=read_f.read()
dic=json.loads(data)
print(dic["name"])
Python常用模块系列的更多相关文章
- Python 常用模块系列(2)--time module and datatime module
import time print (help(time)) #time帮助文档 1. time模块--三种时间表现形式: 1° 时间戳--如:time.time() #从python创立以来,到当 ...
- python 常用模块 time random os模块 sys模块 json & pickle shelve模块 xml模块 configparser hashlib subprocess logging re正则
python 常用模块 time random os模块 sys模块 json & pickle shelve模块 xml模块 configparser hashlib subprocess ...
- python常用模块集合
python常用模块集合 Python自定义模块 python collections模块/系列 Python 常用模块-json/pickle序列化/反序列化 python 常用模块os系统接口 p ...
- Python常用模块之sys
Python常用模块之sys sys模块提供了一系列有关Python运行环境的变量和函数. 常见用法 sys.argv 可以用sys.argv获取当前正在执行的命令行参数的参数列表(list). 变量 ...
- Python常用模块中常用内置函数的具体介绍
Python作为计算机语言中常用的语言,它具有十分强大的功能,但是你知道Python常用模块I的内置模块中常用内置函数都包括哪些具体的函数吗?以下的文章就是对Python常用模块I的内置模块的常用内置 ...
- python——常用模块2
python--常用模块2 1 logging模块 1.1 函数式简单配置 import logging logging.debug("debug message") loggin ...
- python——常用模块
python--常用模块 1 什么是模块: 模块就是py文件 2 import time #导入时间模块 在Python中,通常有这三种方式来表示时间:时间戳.元组(struct_time).格式化的 ...
- Python常用模块——目录
Python常用模块学习 Python模块和包 Python常用模块time & datetime &random 模块 Python常用模块os & sys & sh ...
- python 常用模块之random,os,sys 模块
python 常用模块random,os,sys 模块 python全栈开发OS模块,Random模块,sys模块 OS模块 os模块是与操作系统交互的一个接口,常见的函数以及用法见一下代码: #OS ...
随机推荐
- nginx的安装和负载均衡例子(RHEL/CentOS7.4)
首先安装RHEL/CentOS7.4 mini ,然后关闭防火墙和 selinux ,更新系统(参看配置linux使用本地yum安装源和Redhat7/CentOS7 关闭防火墙和 selinux两个 ...
- tensorflow|tf.train.slice_input_producer|tf.train.Coordinator|tf.train.start_queue_runners
#### ''' tf.train.slice_input_producer :定义样本放入文件名队列的方式[迭代次数,是否乱序],但此时文件名队列还没有真正写入数据 slice_input_prod ...
- SSH服务搭建、账号密码登录远程Linux虚拟机、基于密钥的安全验证(Windows_Xshell,Linux)
问题1:如果是两台虚拟机ping不同且其中一个虚拟机是克隆的另一个,需要更改一下MAC地址,关机状态下 一> "编辑虚拟机设置" 一>" 网络适配器" ...
- VC++DLL动态链接库程序
VC++DLL动态链接库程序 VC++DLL动态链接库程序 C++ DLL 导出函数 使用VS2017等IDE生成dll程序,示例如下: C++ DLL 导出类 1.导出类中第一种方法:简单导出类(不 ...
- 为什么总是弹出报错“百度未授权使用地图API”?
今天打开网站的时候出现了这个问题“百度未授权使用地图API, 可能是因为您提供的密钥不是有效的百度开放平台密钥或此密钥未对本应用的百度地图JavasoriptAPI授权.…”经过研究终于知道什么原因了 ...
- java反射(三)--反射与操作类
一.反射与操作类 在反射机制的处理过程之中不仅仅只是一个实例化对象的处理操作,更多的情况下还有类的组成的操作,任何一个类的基本组成结构:父类(父接口),包,属性,方法(构造方法,普通方法)--获取类的 ...
- Netty 如何实现心跳机制与断线重连?
作者:sprinkle_liz www.jianshu.com/p/1a28e48edd92 心跳机制 何为心跳 所谓心跳, 即在 TCP 长连接中, 客户端和服务器之间定期发送的一种特殊的数据包, ...
- C++ 中的 const、引用和指针的深入分析
1,关于 const 的疑问: 1,const 什么时候为只读变量,什么时候是常量: 1,const 从 C 到 C++ 进化的过程中得到了升级,const 在 C++ 中不仅仅像在 C 中声明一个只 ...
- Python控制台输出带颜色方法
书写格式,和相关说明如下: 举例: print('\033[0;32;40m欢迎使用学生选课系统\033[0m') try: num = int(input('请输入数字选择功能 :')) excep ...
- zoj 3777 Problem Arrangement(壮压+背包)
Problem Arrangement Time Limit: 2 Seconds Memory Limit: 65536 KB The 11th Zhejiang Provincial C ...