《Python》常用内置模块

时间:2023-03-10 08:44:46
《Python》常用内置模块

一、time模块(时间模块)

    三种格式:

      1、时间戳时间(timestamp):浮点数,秒为单位,从1970年1月1日0时距今的时间

          1970.1.1  0:0:0  英国伦敦时间(开始时间)

          1970.1.1  8:0:0  北京时间(东8区)

      2、结构化时间(struct_time): 元组(tm_year(年),tm_mon(月),tm_mday(日),tm_hour(时),tm_min(分),tm_sec(秒),tm_wday(周几,0表示周一),tm_yday(一年中第几天),tm_isdst(是否夏令时))          

      3、格式化时间(Format String):  str数据类型  ‘’2018-9-4‘’

%y 两位数的年份表示(00-99)
%Y 四位数的年份表示(000-9999)
%m 月份(01-12)
%d 月内中的一天(0-31)
%H 24小时制小时数(0-23)
%I 12小时制小时数(01-12)
%M 分钟数(00=59)
%S 秒(00-59)
%a 本地简化星期名称
%A 本地完整星期名称
%b 本地简化的月份名称
%B 本地完整的月份名称
%c 本地相应的日期表示和时间表示
%j 年内的一天(001-366)
%p 本地A.M.或P.M.的等价符
%U 一年中的星期数(00-53)星期天为星期的开始
%w 星期(0-6),星期天为星期的开始
%W 一年中的星期数(00-53)星期一为星期的开始
%x 本地相应的日期表示
%X 本地相应的时间表示
%Z 当前时区的名称
%% %号本身

Python中时间日期格式化符号

# 导入时间模块
import time # 时间戳
print(time.time())
# 1536045748.757072 # 格式化时间字符串
print(time.strftime('%Y-%m-%d %X'))
# 2018-09-04 15:26:06
print(time.strftime('%Y-%m-%d %H:%M:%S'))
# 2018-09-04 15:26:06 # 结构化时间
print(time.localtime())
# time.struct_time(tm_year=2018, tm_mon=9, tm_mday=4, tm_hour=15, tm_min=28, tm_sec=0, tm_wday=1, tm_yday=247, tm_isdst=0)

   小结:时间戳是计算机能够识别的时间;格式化时间是人能够看懂的时间;结构化时间则是用来操作时间的

几种格式之间的转换:

《Python》常用内置模块

时间戳转换成结构化时间:

import time
# 时间戳-->结构化时间
#time.gmtime(时间戳) #UTC时间,与英国伦敦当地时间一致
#time.localtime(时间戳) #当地时间。例如我们现在在北京执行这个方法:与UTC时间相差8小时,UTC时间+8小时 = 北京时间
print(time.gmtime(1500000000))
# time.struct_time(tm_year=2017, tm_mon=7, tm_mday=14, tm_hour=2, tm_min=40, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=0)
print(time.localtime(1500000000))
# time.struct_time(tm_year=2017, tm_mon=7, tm_mday=14, tm_hour=10, tm_min=40, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=0) # 结构化时间-->时间戳
# time.mktime(结构化时间)
time_tuple = time.localtime(1500000000)
print(time_tuple)
# time.struct_time(tm_year=2017, tm_mon=7, tm_mday=14, tm_hour=10, tm_min=40, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=0)
print(time.mktime(time_tuple))
# 1500000000.0

格式化时间与结构化时间互相转换:

import time

# 结构化时间-->格式化时间
# time.strftime('格式定义','结构化时间') 结构化时间参数若不传,则显示当前时间
print(time.strftime('%Y-%m-%d %X'))
# 2018-09-04 16:09:14
print(time.strftime('%Y-%m-%d %X',time.localtime(1500000000)))
# 2017-07-14 10:40:00 # 格式化时间-->结构化时间
# time.strptime(格式化时间字符串,字符串对应的格式)
print(time.strptime('2018-9-4', '%Y-%m-%d'))
# time.struct_time(tm_year=2018, tm_mon=9, tm_mday=4, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=247, tm_isdst=-1)
print(time.strptime('9/4/2018','%m/%d/%Y'))
# time.struct_time(tm_year=2018, tm_mon=9, tm_mday=4, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=247, tm_isdst=-1)

时间戳转换成格式化时间:

import time

# 结构化时间--> %a %b %d %H:%M:%S %Y
# time.asctime(结构化时间) 如果不传参数,直接返回当前时间的格式化串
print(time.asctime(time.localtime(1500000000)))
# Fri Jul 14 10:40:00 2017
print(time.asctime())
# Tue Sep 4 16:26:10 2018 # 时间戳--> %a %b %d %H:%M:%S %Y
# time.ctime(时间戳) 如果不传参数,直接返回当前时间的格式化串
print(time.ctime())
# Tue Sep 4 16:29:00 2018
print(time.ctime(1500000000))
# Fri Jul 14 10:40:00 2017
import time

t1 = time.mktime(time.strptime('2017-5-1 11:13:44','%Y-%m-%d %H:%M:%S'))
t2 = time.mktime(time.strptime('2018-9-4 16:33:01','%Y-%m-%d %H:%M:%S'))
t3 = t2 - t1
struct_time = time.gmtime(t3)
print('过去了%d年%d月%d天%d小时%d分钟%d秒' % (struct_time.tm_year-1970,struct_time.tm_mon-1,
struct_time.tm_mday-1,struct_time.tm_hour,
struct_time.tm_min,struct_time.tm_sec))
# 过去了1年4月6天5小时19分钟17秒

计算时间差

# 写函数,计算本月1号的时间戳时间
import time
def get_timestamp():
fmt_time = time.strftime('%Y-%m-1') # 本月1号
struct = time.strptime(fmt_time,'%Y-%m-%d')
res = time.mktime(struct)
return res
print(get_timestamp())
# 1535731200.0

计算本月1号的时间戳时间

二、random模块(随机数模块)    

import random

# 取随机整数
print(random.randint(1,10)) # 1-10都能取
print(random.randrange(1,10)) # 只能取1-9,取不到10
print(random.randrange(1,100,2)) # 1-99的奇数
print(random.randrange(2,100,2)) # 2-99的偶数 # 取随机小数
print(random.random()) # 0-1之间的浮点数
print(random.uniform(1,10)) # 1-10之间的浮点数 # 从一个列表中随机抽取
lst = [1,2,3,4,5,('a','b'),'cc','dd']
print(random.choice(lst)) # 以列表里的每个元素为单位取
print(random.choice(range(100))) # 0-99的列表中取一个值
print(random.sample(lst,3)) # 列表中随机取3个元素 # 乱序
lst = [1,2,3,4,5,('a','b'),'cc','dd']
random.shuffle(lst)
print(lst) # 在原有列表的基础上打乱顺序,不产生新列表
import random

# 6位数字验证码
def get_code(n=6):
code = ''
for i in range(n):
num = random.randint(0,9)
code += str(num)
return code
ret1 = get_code() # 默认6位
ret2 = get_code(4) # 改成4位
print(ret1,ret2) # 265326 1548 # 6位验证码,包含数字,大小写字母
def get_code(n=6):
code = ''
for i in range(n):
num = str(random.randint(0,9))
alpha_upper = chr(random.randint(65,90)) # 大写字母的ascii码是65-90
alpha_lower = chr(random.randint(97,122)) # 小写字母的ascii码是97-122
c = random.choice([num,alpha_upper,alpha_lower])
code += c
return code
ret1 = get_code()
ret2 = get_code(4)
print(ret1,ret2) # P9njz1 12Hw # 6位验证码,包含数字,大小写字母(可纯数字)
def get_code(n = 6,alph_flag = True):
code = ''
for i in range(n):
c = str(random.randint(0,9))
if alph_flag:
alpha_upper = chr(random.randint(65, 90))
alpha_lower = chr(random.randint(97, 122))
c = random.choice([c,alpha_upper,alpha_lower])
code += c
return code
ret1 = get_code() # 默认6位数字大小写字母组成
ret2 = get_code(6,False) # 6位纯数字
ret3 = get_code(4,False) # 4位纯数字
print(ret1,ret2,ret3) # wn27w4 808732 1524

生成随机验证码

三、os模块

    os模块是与操作系统交互的一个接口

import os

# 文件和文件夹的操作
os.remove() # 删除一个文件
os.rename("oldname","newname") # 重命名文件/目录 os.mkdir('dirname') # 相对路径下生成单级目录;相当于shell中mkdir dirname
os.makedirs('dirname1/dirname2') # 相对路径下生成多级目录
os.rmdir('dirname') # 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
os.removedirs('dirname1/dirname2') # 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推 os.listdir('D:\python') # 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
os.stat('path/filename') # 获取文件/目录信息 # 执行操作系统命令
os.system(命令) # 运行shell命令,直接显示
os.popen(命令).read() # 运行shell命令,获取执行结果 # 和Python程序的工作目录相关的
os.getcwd() # 获取当前工作目录,即当前python脚本工作的目录路径
os.chdir("dirname") # 改变当前脚本工作目录;相当于shell下cd # os.path系列(路径的操作)
path = 'D:/python/day23/day23.py'
os.path.join('D:/python','day23') # 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
os.path.split(path) # 将path分割成目录和文件名二元组返回
os.path.dirname(path) # 返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.basename(path) # 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.exists(path) # 如果path存在,返回True;如果path不存在,返回False
os.path.isfile(path) # 如果path是一个存在的文件,返回True。否则返回False
os.path.isdir(path) # 如果path是一个存在的目录,则返回True。否则返回False
os.path.abspath(path) # 返回path规范化的绝对路径
os.path.getsize(path) # 返回path的大小
os.path.isabs(path) # 如果path是绝对路径,返回True
os.path.getatime(path) # 返回path所指向的文件或者目录的最后访问时间
os.path.getmtime(path) # 返回path所指向的文件或者目录的最后修改时间 # __file__文件中的一个内置变量,描述的是这个文件的绝对路径
stat 结构:

st_mode: inode 保护模式
st_ino: inode 节点号。
st_dev: inode 驻留的设备。
st_nlink: inode 的链接数。
st_uid: 所有者的用户ID。
st_gid: 所有者的组ID。
st_size: 普通文件以字节为单位的大小;包含等待某些特殊文件的数据。
st_atime: 上次访问的时间。
st_mtime: 最后一次修改的时间。
st_ctime: 由操作系统报告的"ctime"。在某些系统上(如Unix)是最新的元数据更改的时间,在其它系统上(如Windows)是创建时间(详细信息参见平台的文档)。

stat 结构:

os.sep    输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
os.linesep 输出当前平台使用的行终止符,win下为"\r\n",Linux下为"\n"
os.pathsep 输出用于分割文件路径的字符串 win下为;,Linux下为:
os.name 输出字符串指示当前使用平台。win->'nt'; Linux->'posix'

os模块的属性

四、sys模块

    sys模块是与Python解释器交互的一个接口

import sys

sys.argv           # 命令行参数List,第一个元素是程序本身路径
sys.exit(n) # 退出程序,正常退出时exit(0),错误退出sys.exit(1)
sys.version # 获取Python解释程序的版本信息
sys.platform # 返回操作系统平台名称
sys.modules # 查看当前内存空间中所有的模块,和这个模块的内存空间 sys.path # 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
# 一个模块能否被导入,就看这个模块所在的目录在不在sys.path路径中
# 内置模块和第三方扩展模块都不需要我们处理sys.path就可以直接使用
# 自定义的模块的导入工作需要自己手动的修改sys.path
import sys
try:
sys.exit(1)
except SystemExit as e:
print(e)

异常处理和status