首页 > 技术文章 > Python常用模块系列

so-cool 2017-11-10 16:28 原文

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"])

  

推荐阅读