目录
一:定义
某个功能代码的集合,为了完成业务需求,采用拿来主义,直接调用即可,把更多的时间放在逻辑处理。模块一般分为三种:
- 自定义模块
- 内置标准库
- 开源模块
使用模块的好处
- 提高代码的可维护性
- 编写代码不需要从0开始
模块和包导入方法
模块是为了组织函数方法,就是一个*.py;包是为了组织模块,是多个模块的集合,包含一个__init__.py文件
import 导入某个模块名(通过sys.path找到对应的文件)
import 导入某个包 执行__init__.py文件
from 模块 import 方法
from 包 import 模块
from 包.模块 import 方法
路径问题
在sys.path加入包的路径
import os,sys
BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
'''
__file__:指的是当前文件位置的相对路径
os.path.abspath(__file__):返回当前文件位置的绝对路径
os.path.dirname(os.path.abspath(__path__)):返回当前文件路径的上一级路径
'''
from module.main1 import main
main()
'''
也可以使用这种方法
from moudule import main1
main1.main()
'''
二:time
时间的相关操作,有三种表现形式
- 时间戳 1970年1月1日之后的秒 即:time.time()
- 格式化的字符串 2019-11-11-11 即:time.strftime('%Y-%m-%d')
- 结构化时间 元组包含了:年月日等 即: time.localtime() 北京时间 (time.gmtime() UTC时间)
time.strftime("%Y{a}-%m{b}-%d{c} %X", time.localtime()).format(a='年',b='月',c='日')
time.strptime('2019-05-05 16:37:06', '%Y-%m-%d %X')
输出指定字段如年使用a.tm_year,其他类似
b=time.mktime(a) 把struct_time转换为时间戳
输入print(help(time))可出现如下提示
%y (00-99)
%Y Year with century as a decimal number.
%m Month as a decimal number [01,12].
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23]. %I(01-12)
%M Minute as a decimal number [00,59].
%S Second as a decimal number [00,61].
%a Locale's abbreviated weekday name.
%A Locale's full weekday name.
%b Locale's abbreviated month name.
%B Locale's full month name.
三:datetime模块
进行时间运算最方便
datetime.datetime.now() 输出一个标准时间:2019-01-07 16:44:57.614705
四:random模块
import random
print(random.random()) #产生0,1的小数
print(random.randint(1,2)) #产生1,2的整数,包括2
print(random.randrange(1,10)) #产生一个范围的整数,不包括10
产生四位随机大小验证码
import random
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 += str(temp)
print(checkcode)