1.模块概念
模块就是存放着各种写好的功能的模块的文件,通过import引入模块过后我们就可以使用该模块写好的功能,也就是方法和变量。如果是使用的话了解到这里就够了,详细模块和包的操作可以看:python篇 模块和包
2.模块分类
通过创建者来分:
名称 | 特性(举例) |
---|---|
py内置模块 | random os os.path |
第三方模块 | 需要安装(1.在线安装 2.离线安装 下载安装包) |
自定义模块 | 可以自己瞎搞搞坏也没啥 |
提一下
#在线安装
python -m pip install 模块名称
3.导入模块方式
方式 | 用法 |
---|---|
import | import 模块名字 |
import as | import 模块名字 as 别名 |
from | from functools import partial |
#导入模块
import 模块名字
#导入并设置别名
import 模块名字 as 别名
#通过fromda导入模块
from functools import partial
4.常用模块
4.1. random模块
4.1.1.random功能或概念
先用dir看看其功能
dir(random)
[‘BPF’, ‘LOG4’, ‘NV_MAGICCONST’, ‘RECIP_BPF’, ‘Random’, ‘SG_MAGICCONST’, ‘SystemRandom’, ‘TWOPI’, ‘_Sequence’, ‘_Set’, ‘all’, ‘builtins’, ‘cached’, ‘doc’, ‘file’, ‘loader’, ‘name’, ‘package’, ‘spec’, ‘_accumulate’, ‘_acos’, ‘_bisect’, ‘_ceil’, ‘_cos’, ‘_e’, ‘_exp’, ‘_floor’, ‘_inst’, ‘_log’, ‘_os’, ‘_pi’, ‘_random’, ‘_repeat’, ‘_sha512’, ‘_sin’, ‘_sqrt’, ‘_test’, ‘_test_generator’, ‘_urandom’, ‘_warn’, ‘betavariate’, ‘choice’, ‘choices’, ‘expovariate’, ‘gammavariate’, ‘gauss’, ‘getrandbits’, ‘getstate’, ‘lognormvariate’, ‘normalvariate’, ‘paretovariate’, ‘randbytes’, ‘randint’, ‘random’, ‘randrange’, ‘sample’, ‘seed’, ‘setstate’, ‘shuffle’, ‘triangular’, ‘uniform’, ‘vonmisesvariate’, ‘weibullvariate’]
4.1.2.random常用的内置方法
名称 | 作用 |
---|---|
randint() | 产生随机整数[m,n] (包含终点) |
uniform() | 产生正态分布的随机数(不太常用) |
random() | 产生0~1之间的随机数 |
randrange | 产生的是一个范围内的随机数(不包含终点) |
choice() | 在序列(有序)中筛选元素 |
help(random.randint)可用于查看功能
4.2.math模块
4.2.1.math功能或概念
作用:主要用于数学运算
dir(math)
[‘doc’, ‘loader’, ‘name’, ‘package’, ‘spec’, ‘acos’, ‘acosh’, ‘asin’, ‘asinh’, ‘atan’, ‘atan2’, ‘atanh’, ‘ceil’, ‘comb’, ‘copysign’, ‘cos’, ‘cosh’, ‘degrees’, ‘dist’, ‘e’, ‘erf’, ‘erfc’, ‘exp’, ‘expm1’, ‘fabs’, ‘factorial’, ‘floor’, ‘fmod’, ‘frexp’, ‘fsum’, ‘gamma’, ‘gcd’, ‘hypot’, ‘inf’, ‘isclose’, ‘isfinite’, ‘isinf’, ‘isnan’, ‘isqrt’, ‘lcm’, ‘ldexp’, ‘lgamma’, ‘log’, ‘log10’, ‘log1p’, ‘log2’, ‘modf’, ‘nan’, ‘nextafter’, ‘perm’, ‘pi’, ‘pow’, ‘prod’, ‘radians’, ‘remainder’, ‘sin’, ‘sinh’, ‘sqrt’, ‘tan’, ‘tanh’, ‘tau’, ‘trunc’, ‘ulp’]
4.2.2.math常用的内置方法
名称 | 作用 |
---|---|
ceil() | 向上取整 |
floor() | 向下取整 |
e | 属性 自然常数 |
fabs() | 取绝对值(和全局函数abs功能一样) |
fmod() | 求模运算 |
isnan() | 判断是否数字 |
isfinite() | 判断是否无限 |
pi | 属性 圆周率 |
pow() | 计算幂次方 |
sqrt() | 平方根 |
举例:
ceil()-------- 向上取整
>>> help(math.ceil)
Help on built-in function ceil in module math:
ceil(x, /)
Return the ceiling of x as an Integral.
This is the smallest integer >= x.
>>> t=7.2
>>> math.ceil(t)
8
floor()-------向下取整
>>> help(math.floor)
Help on built-in function floor in module math:
floor(x, /)
Return the floor of x as an Integral.
This is the largest integer <= x.
>>> t
7.2
>>> math.floor(t)
7
isnan()--------判断是否数字(js nan数据类型:not a number 是数字返回false 否则)
Help on built-in function isnan in module math:
isnan(x, /)
Return True if x is a NaN (not a number), and False otherwise.
isfinite()---------判断是否无限
>>> help(math.isfinite)
Help on built-in function isfinite in module math:
isfinite(x, /)
Return True if x is neither an infinity nor a NaN, and False otherwise.
4.3.os模块
4.3.1.os功能或概念
操作系统文件的模块,首先用dir方法看看方法
dir(os)
[‘DirEntry’, ‘F_OK’, ‘GenericAlias’, ‘Mapping’, ‘MutableMapping’, ‘O_APPEND’, ‘O_BINARY’, ‘O_CREAT’, ‘O_EXCL’, ‘O_NOINHERIT’, ‘O_RANDOM’, ‘O_RDONLY’, ‘O_RDWR’, ‘O_SEQUENTIAL’, ‘O_SHORT_LIVED’, ‘O_TEMPORARY’, ‘O_TEXT’, ‘O_TRUNC’, ‘O_WRONLY’, ‘P_DETACH’, ‘P_NOWAIT’, ‘P_NOWAITO’, ‘P_OVERLAY’, ‘P_WAIT’, ‘PathLike’, ‘R_OK’, ‘SEEK_CUR’, ‘SEEK_END’, ‘SEEK_SET’, ‘TMP_MAX’, ‘W_OK’, ‘X_OK’, ‘_AddedDllDirectory’, ‘_Environ’, ‘all’, ‘builtins’, ‘cached’, ‘doc’, ‘file’, ‘loader’, ‘name’, ‘package’, ‘spec’, ‘_check_methods’, ‘_execvpe’, ‘_exists’, ‘_exit’, ‘_fspath’, ‘_get_exports_list’, ‘_walk’, ‘_wrap_close’, ‘abc’, ‘abort’, ‘access’, ‘add_dll_directory’, ‘altsep’, ‘chdir’, ‘chmod’, ‘close’, ‘closerange’, ‘cpu_count’, ‘curdir’, ‘defpath’, ‘device_encoding’, ‘devnull’, ‘dup’, ‘dup2’, ‘environ’, ‘error’, ‘execl’, ‘execle’, ‘execlp’, ‘execlpe’, ‘execv’, ‘execve’, ‘execvp’, ‘execvpe’, ‘extsep’, ‘fdopen’, ‘fsdecode’, ‘fsencode’, ‘fspath’, ‘fstat’, ‘fsync’, ‘ftruncate’, ‘get_exec_path’, ‘get_handle_inheritable’, ‘get_inheritable’, ‘get_terminal_size’, ‘getcwd’, ‘getcwdb’, ‘getenv’, ‘getlogin’, ‘getpid’, ‘getppid’, ‘isatty’, ‘kill’, ‘linesep’, ‘link’, ‘listdir’, ‘lseek’, ‘lstat’, ‘makedirs’, ‘mkdir’, ‘name’, ‘open’, ‘pardir’, ‘path’, ‘pathsep’, ‘pipe’, ‘popen’, ‘putenv’, ‘read’, ‘readlink’, ‘remove’, ‘removedirs’, ‘rename’, ‘renames’, ‘replace’, ‘rmdir’, ‘scandir’, ‘sep’, ‘set_handle_inheritable’, ‘set_inheritable’, ‘spawnl’, ‘spawnle’, ‘spawnv’, ‘spawnve’, ‘st’, ‘startfile’, ‘stat’, ‘stat_result’, ‘statvfs_result’, ‘strerror’, ‘supports_bytes_environ’, ‘supports_dir_fd’, ‘supports_effective_ids’, ‘supports_fd’, ‘supports_follow_symlinks’, ‘symlink’, ‘sys’, ‘system’, ‘terminal_size’, ‘times’, ‘times_result’, ‘truncate’, ‘umask’, ‘uname_result’, ‘unlink’, ‘unsetenv’, ‘urandom’, ‘utime’, ‘waitpid’, ‘waitstatus_to_exitcode’, ‘walk’, ‘write’]
当然本人没有全数掌握,太多了,也不一定用得到
4.3.2 os常用方法
名称 | 作用 |
---|---|
chdir() | 修改工作目录(没加()的是属性) |
curdir | 返回当前目录,返回的是相对路径 |
chmod() | 修改权限(主要用于linux系统) |
close() | 关闭文件路径(一般不用) |
cpu_count() | 返回cpu核对应线程数(2核4线程) |
getcwd() | 获取当前路径,返回的是绝对路径 |
getpid() | 获取当前进程的编号 |
getppid() | 返回当前进程父进程编号 |
kill() | 通过进程编号杀死进程(慎重使用) |
linesep | 获取系统当前对应换行符 |
listdir() | 对应目录下所有的文件(包含隐藏) |
mkdir() | 创建目录 只能创建一层(下一层) |
makedirs() | 创建目录(支持多层目录) |
open() | 创建文件,等价于open全局函数 lo详细介绍 |
pathsep | 获取环境变量分隔符 |
sep | 获取当前路径的分隔符 |
remove() | 删除文件 |
removedirs() | 删除目录 支持多级删除 递归原理 |
system() | 执行终端命令 如os.system(“cls”) |
open() | 创建文件,等价于open全局函数 lo详细介绍 |
open() | 创建文件,等价于open全局函数 lo详细介绍 |
这里同样提一下一些特殊的或没表示清楚的:
curdir-------属性 获取当前目录,返回的是相对路径(返回绝对路径os.path.abspath(os.curdir))
>>> import os
>>> os.chdir("D://")
>>> os.curdir
'.'
>>> os.path.abspath(os.curdir)
'D:\\'
>>>
4.4.os.path模块
4.4.1.os.path功能或概念
[‘all’, ‘builtins’, ‘cached’, ‘doc’, ‘file’, ‘loader’, ‘name’, ‘package’, ‘spec’, ‘_abspath_fallback’, ‘_get_bothseps’, ‘_getfinalpathname’, ‘_getfinalpathname_nonstrict’, ‘_getfullpathname’, ‘_getvolumepathname’, ‘_nt_readlink’, ‘_readlink_deep’, ‘abspath’, ‘altsep’, ‘basename’, ‘commonpath’, ‘commonprefix’, ‘curdir’, ‘defpath’, ‘devnull’, ‘dirname’, ‘exists’, ‘expanduser’, ‘expandvars’, ‘extsep’, ‘genericpath’, ‘getatime’, ‘getctime’, ‘getmtime’, ‘getsize’, ‘isabs’, ‘isdir’, ‘isfile’, ‘islink’, ‘ismount’, ‘join’, ‘lexists’, ‘normcase’, ‘normpath’, ‘os’, ‘pardir’, ‘pathsep’, ‘realpath’, ‘relpath’, ‘samefile’, ‘sameopenfile’, ‘samestat’, ‘sep’, ‘split’, ‘splitdrive’, ‘splitext’, ‘stat’, ‘supports_unicode_filenames’, ‘sys’]
同样有三种方法可以引用
import os.path
from os import path
import os.path as p
4.4.2.os.path常用方法
名称 | 作用 |
---|---|
abspath(相对路径) | 返回相对路径的绝对路径 |
altsep | 返回python中分隔符 |
basename() | 返回文件名称 |
dirname | 文件返回目录 |
altsep | 返回python中分隔符 |
exists | 返回文件或目录是否存在 |
getctime | 获取创建时间 |
getmtime | 获取修改时间 |
getsize | 获取文件大小,单位字节 |
isdir | 判断path(目录)是否存在 |
isfile | 判断文件是否存在 |
islink | 判断是不是链接 |
ismount | 判断是不是挂载文件 |
join | 拼接路径 前路加后路 |
sep | 返回路径分隔符` |
split | 分割路径,文件和目录分开 |
relpath | 返回真正路径,绝对路径 |
部分举例:
>>> p.abspath("D:\java\训练\ch1\\Hello.class")
'D:\\java\\训练\\ch1\\Hello.class'
>>> p.abspath(".")
'D:\\python\\练习'
>>> p.altsep
'/'
>>> p.basename("d://ch1")
'ch1'
>>> p.basename("D:\java\训练\ch1\\Hello.class")
'Hello.class'
>>> p.dirname("D:\java\训练\ch1\\Hello.class")
'D:\\java\\训练\\ch1'
exists----------返回文件或目录是否存在
>>> p.exists("D:\java\训练\ch1\\Hello.class")
True
getctime---------获取创建时间
>>> p.getctime("D:\java\训练\ch1\\Hello.class")
1636788601.1296935
getmtime --------获取修改时间
>>> p.getmtime("D:\java\训练\ch1\\Hello.class")
1636788601.133694
getsize----------获取文件大小,单位字节
>>> p.getsize("D:\java\训练\ch1\\Hello.class")
416
isdir-----------判断path(目录)是否存在
>>> p.isdir("D:\java\训练\ch1\\Hello.class")
False
>>> p.isdir("D:\java\训练\ch1")
True
isfile-----------判断文件是否存在
>>> p.isfile("D:\java\训练\ch1\\Hello.class")
True
>>> p.isfile("D:\java\训练\ch1")
False
islink-----------判断是不是链接
ismount---------判断是不是挂载文件
join-------------- 拼接路径 前路加后路
>>> p.join("d://","word")
'd://word'
sep-------------- 返回路径分隔符
>>> p.sep
'\\'
split------------分割路径,文件和目录分开
在这里插入代码片>>> p.split("D:\java\训练\ch1\\Hello.class")
('D:\\java\\训练\\ch1', 'Hello.class')
relpath----------返回真正路径,绝对路径
>>> p.relpath("D:\java\训练\ch1\\Hello.class")
'..\\..\\java\\训练\\ch1\\Hello.class'
>>> p.relpath(".")
'.'
练习
结合os、os.path,以及函数
实现给出一个路径,遍历当前路径下所有的文件和文件夹,打印出所有文件
#遍历文件
import os
import os.path as p
def Scanner_file(url):
dirlist=os.listdir(url)
#print(dirlist)
for i in dirlist:
real_url=p.join(url,i)
if p.isfile(real_url):
print(p.abspath(real_url))
elif p.isdir(real_url):
Scanner_file(real_url)
else:
print("其他情况")
pass
Scanner_file("d://")
4.5.sys模块
4.5.1.sys功能或方法
dir(sys)
[‘breakpointhook’, ‘displayhook’, ‘doc’, ‘excepthook’, ‘interactivehook’, ‘loader’, ‘name’, ‘package’, ‘spec’, ‘stderr’, ‘stdin’, ‘stdout’, ‘unraisablehook’, ‘_base_executable’, ‘_clear_type_cache’, ‘_current_frames’, ‘_debugmallocstats’, ‘_enablelegacywindowsfsencoding’, ‘_framework’, ‘_getframe’, ‘_git’, ‘_home’, ‘_xoptions’, ‘addaudithook’, ‘api_version’, ‘argv’, ‘audit’, ‘base_exec_prefix’, ‘base_prefix’, ‘breakpointhook’, ‘builtin_module_names’, ‘byteorder’, ‘call_tracing’, ‘copyright’, ‘displayhook’, ‘dllhandle’, ‘dont_write_bytecode’, ‘exc_info’, ‘excepthook’, ‘exec_prefix’, ‘executable’, ‘exit’, ‘flags’, ‘float_info’, ‘float_repr_style’, ‘get_asyncgen_hooks’, ‘get_coroutine_origin_tracking_depth’, ‘getallocatedblocks’, ‘getdefaultencoding’, ‘getfilesystemencodeerrors’, ‘getfilesystemencoding’, ‘getprofile’, ‘getrecursionlimit’, ‘getrefcount’, ‘getsizeof’, ‘getswitchinterval’, ‘gettrace’, ‘getwindowsversion’, ‘hash_info’, ‘hexversion’, ‘implementation’, ‘int_info’, ‘intern’, ‘is_finalizing’, ‘maxsize’, ‘maxunicode’, ‘meta_path’, ‘modules’, ‘path’, ‘path_hooks’, ‘path_importer_cache’, ‘platform’, ‘platlibdir’, ‘prefix’, ‘ps1’, ‘ps2’, ‘pycache_prefix’, ‘set_asyncgen_hooks’, ‘set_coroutine_origin_tracking_depth’, ‘setprofile’, ‘setrecursionlimit’, ‘setswitchinterval’, ‘settrace’, ‘stderr’, ‘stdin’, ‘stdout’, ‘thread_info’, ‘unraisablehook’, ‘version’, ‘version_info’, ‘warnoptions’, ‘winver’]
4.5.2.sys常用内置方法
名称 | 作用 |
---|---|
api_version | 获取python内部版本号 |
argv | 接受脚本参数 |
copyright | 获取python版本信息 |
eixt | sys.eixt 退出系统 |
getdefaultencoding | -获取默认编码,python 3 utf-8 |
getfilesystemencoding | 获取系统编码 |
getrecursionlimit | 获取python对递归的限制层数 |
setrecursionlimit | 重设递归限制次数,慎重使用 |
getrefcount | 获取对象引用计数,对象默认一次 |
getwindowsversion | 获取当前窗口版本信息 |
version | 获取版本信息 |
api_version------获取python内部版本号
>>> sys.api_version
1013
argv------------接受脚本参数
import sys
print(sys.argv)
D:\python\练习>python domesys.py 12 hh1 dsfasdfas
['domesys.py', '12', 'hh1', 'dsfasdfas']
#遍历文件
import os
import os.path as p
import sys
def Scanner_file(url):
dirlist=os.listdir(url)
#print(dirlist)
for i in dirlist:
real_url=p.join(url,i)
if p.isfile(real_url):
print(p.abspath(real_url))
elif p.isdir(real_url):
Scanner_file(real_url)
else:
print("其他情况")
pass
arg=sys.argv
if len(arg)<2:
print("请输入脚本参数")
else:
for i in range(1,len(arg)):
Scanner_file(arg[i])
#改进
copyright-------获取python版本信息
sys.copyright
‘Copyright © 2001-2020 Python Software Foundation.\nAll Rights Reserved.\n\nCopyright © 2000 BeOpen.com.\nAll Rights Reserved.\n\nCopyright © 1995-2001 Corporation for National Research Initiatives.\nAll Rights Reserved.\n\nCopyright © 1991-1995 Stichting Mathematisch Centrum, Amsterdam.\nAll Rights Reserved.’
eixt-----------sys.eixt 退出系统
>>> sys.exit()
D:\python\练习>
getdefaultencoding-----获取默认编码,python 3 utf-8
>>> sys.getdefaultencoding()
'utf-8'
getfilesystemencoding------获取系统编码
>>> sys.getfilesystemencoding()
'utf-8'
getrecursionlimit--------获取python对递归的限制层数
>>> sys.getrecursionlimit()
1000
setrecursionlimit-------重设递归限制次数,慎重使用
>>> sys.setrecursionlimit(100)
>>> sys.getrecursionlimit()
100
getrefcount------获取对象引用计数,对象默认一次
>>> sys.getrefcount(int)
68
getwindowsversion------获取当前窗口版本信息
>>> sys.getwindowsversion()
sys.getwindowsversion(major=10, minor=0, build=10240, platform=2, service_pack='')
version-----获取版本信息
>>> sys.version
'3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)]'
4.6.加密模块
在学习加密模块前需要理解一些概念
4.6.1 垃圾回收机制
以引用计数为主,以标记清除和分代收集为辅
java中以标记清除为主,以引用计数和分代收集为辅
4.6.2.加密算法的介绍
所谓加密算法呢,即是加密算法,懂了不?不懂正常,我也不懂
加密算法按是否可逆可以分为可逆算法和不可逆算法
4.6.3.可逆算法
可逆算法按是否使用同一个密码可分为对称加密和不对称加密
4.6.3.1.对称加密
解密和加密的密钥是一样的 可暴力破解
4.6.3.2不对称加密
加密和解密使用的一对密钥
4.6.4.不可逆算法
如hash算法
特点:不可逆,结果是唯一的 如md5加密
4.7.加密库
4.7.1.hashlib库
dir(hashlib)
[‘all’, ‘__block_openssl_constructor’, ‘__builtin_constructor_cache’, ‘builtins’, ‘cached’, ‘doc’, ‘file’, ‘__get_builtin_constructor’, ‘loader’, ‘name’, ‘package’, ‘spec’, ‘_hashlib’, ‘algorithms_available’, ‘algorithms_guaranteed’, ‘blake2b’, ‘blake2s’, ‘md5’, ‘new’, ‘pbkdf2_hmac’, ‘scrypt’, ‘sha1’, ‘sha224’, ‘sha256’, ‘sha384’, ‘sha3_224’, ‘sha3_256’, ‘sha3_384’, ‘sha3_512’, ‘sha512’, ‘shake_128’, ‘shake_256’]
hashlib.md5()
>>> import hashlib
>>> md5=hashlib.md5()
>>> md5
<md5 _hashlib.HASH object @ 0x0000005E7DC2D9F0>
>>> md5=hashlib.md5("2131")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Unicode-objects must be encoded before hashing
>>> md5=hashlib.md5("2131".encode("utf-8"))
>>> md5
<md5 _hashlib.HASH object @ 0x0000005E7DC76130>
>>> md5.hexdigest()
'a869ccbcbd9568808b8497e28275c7c8'
破解密码:
方法一:先md5的值存下来,用于对比
方法二:https://cmd5.com/
盐值混淆
>>> md5=hashlib.md5("12345678".encode("utf-8"))
>>> md5
<md5 _hashlib.HASH object @ 0x0000005E7DC2D9F0>
>>> md5.update("&&**((%%".encode("utf-8"))
>>> md5.hexdigest()
'bcc2bf177a7ebeb2ea08448babace581'
盐值越复杂,解密可能性越小,密码越安全·
4.7.2. hmac 对称加密
也是哈希加密库,并且用到了对称加密
参数:第一个参数是要加密的字符串,第二个参数是盐值,第三个参数是加密方式
dir(hmac)
[‘HMAC’, ‘builtins’, ‘cached’, ‘doc’, ‘file’, ‘loader’, ‘name’, ‘package’, ‘spec’, ‘_hashlib’, ‘_hashopenssl’, ‘_openssl_md_meths’, ‘_warnings’, ‘compare_digest’, ‘digest’, ‘digest_size’, ‘new’, ‘trans_36’, ‘trans_5C’]
>>> md5=hmac.new("12345".encode("utf-8"),"32".encode("utf-8"),hashlib.md5)
>>> md5
<hmac.HMAC object at 0x0000005E7E3086D0>
>>> md5.hexdigest()
'8966471b3a8b417448e42c19290cbcf2'
首先使用对称加密(密钥是盐值),在进行了一次md5加密(hash加密),非常安全
4.8.时间模块
4.8.1.time模块
4.8.1.1.time功能或概念
操作时间和日期的模块
dir(time)
[’_STRUCT_TM_ITEMS’, ‘doc’, ‘loader’, ‘name’, ‘package’, ‘spec’, ‘altzone’, ‘asctime’, ‘ctime’, ‘daylight’, ‘get_clock_info’, ‘gmtime’, ‘localtime’, ‘mktime’, ‘monotonic’, ‘monotonic_ns’, ‘perf_counter’, ‘perf_counter_ns’, ‘process_time’, ‘process_time_ns’, ‘sleep’, ‘strftime’, ‘strptime’, ‘struct_time’, ‘thread_time’, ‘thread_time_ns’, ‘time’, ‘time_ns’, ‘timezone’, ‘tzname’]
4.8.1.2.time常用内置方法
名称 | 功能 |
---|---|
asctime | 获取当前时间 |
ctime | 获取当前时间 |
localtime | 获取本地时间 |
sleep | 休眠时间,单位秒 |
time | 获取当前系统时间戳,单位是秒 |
strftime | 将时间对象格式化为字符串 f–表示—format |
strptime | 转换时间为对象 |
asctime--------获取当前时间
>>> time.asctime()
'Sun Nov 14 16:45:01 2021'
ctime--------获取当前时间
>>> time.ctime()
'Sun Nov 14 16:45:08 2021'
>>>
localtime-------获取本地时间
>>> time.localtime()
time.struct_time(tm_year=2021, tm_mon=11, tm_mday=14, tm_hour=16, tm_min=46, tm_sec=2, tm_wday=6, tm_yday=318, tm_isdst=0)
>>> litime=time.localtime()
>>> litime.tm_year
2021
>>> litime.tm_mon
11
>>> print("%s-%s-%s %s:%s:%s"%(litime.tm_year,litime.tm_mon,litime.tm_mday,litime.tm_hour,litime.tm_min,litime.tm_sec))
2021-11-14 16:46:29
sleep-------休眠时间,单位秒
>>> time.sleep(3)
>>>
time--------获取当前系统时间戳,单位是秒
>>> time.time()
1636880136.733563
>>>
strftime-------将时间对象格式化为字符串 f-----format
help(time.strftime)
Help on built-in function strftime in module time:
strftime(…)
strftime(format[, tuple]) -> string
Convert a time tuple to a string according to a format specification.
See the library reference manual for formatting codes. When the time tuple
is not present, current time as returned by localtime() is used.
Commonly used format cod
%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].
%M Minute as a decimal number [00,59].
%S Second as a decimal number [00,61].
%z Time zone offset from UTC.
%a Locale’s abbreviated weekday name.
%A Locale’s full weekday name.
%b Locale’s abbreviated month name.
%B Locale’s full month name.
%c Locale’s appropriate date and time representation.
%I Hour (12-hour clock) as a decimal number [01,12].
%p Locale’s equivalent of either AM or PM.
Other codes may be available on your platform. See documentation for
the C library strftime function.
>>> time.strftime("%Y-%m-%d")
'2021-11-14'
strptime------转换对象
help(time.strptime)
Help on built-in function strptime in module time:
strptime(…)
strptime(string, format) -> struct_time
Parse a string to a time tuple according to a format specification.
See the library reference manual for formatting codes (same as
strftime()).
Commonly used format codes:
%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].
%M Minute as a decimal number [00,59].
%S Second as a decimal number [00,61].
%z Time zone offset from UTC.
%a Locale’s abbreviated weekday name.
%A Locale’s full weekday name.
%b Locale’s abbreviated month name.
%B Locale’s full month name.
%c Locale’s appropriate date and time representation.
%I Hour (12-hour clock) as a decimal number [01,12].
%p Locale’s equivalent of either AM or PM.
Other codes may be available on your platform. See documentation for
the C library strftime function.
>>> s="2019-11-11 08:00:00"
>>> type(s)
<class 'str'>
>>> time.strptime(s,"%Y-%m-%d %H:%M:%S")
time.struct_time(tm_year=2019, tm_mon=11, tm_mday=11, tm_hour=8, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=315, tm_isdst=-1)
4.8.2.datetime模块
datetime是time的补充
dir(datetime)
[‘add’, ‘class’, ‘delattr’, ‘dir’, ‘doc’, ‘eq’, ‘format’, ‘ge’, ‘getattribute’, ‘gt’, ‘hash’, ‘init’, ‘init_subclass’, ‘le’, ‘lt’, ‘ne’, ‘new’, ‘radd’, ‘reduce’, ‘reduce_ex’, ‘repr’, ‘rsub’, ‘setattr’, ‘sizeof’, ‘str’, ‘sub’, ‘subclasshook’, ‘astimezone’, ‘combine’, ‘ctime’, ‘date’, ‘day’, ‘dst’, ‘fold’, ‘fromisocalendar’, ‘fromisoformat’, ‘fromordinal’, ‘fromtimestamp’, ‘hour’, ‘isocalendar’, ‘isoformat’, ‘isoweekday’, ‘max’, ‘microsecond’, ‘min’, ‘minute’, ‘month’, ‘now’, ‘replace’, ‘resolution’, ‘second’, ‘strftime’, ‘strptime’, ‘time’, ‘timestamp’, ‘timetuple’, ‘timetz’, ‘today’, ‘toordinal’, ‘tzinfo’, ‘tzname’, ‘utcfromtimestamp’, ‘utcnow’, ‘utcoffset’, ‘utctimetuple’, ‘weekday’, ‘year’]
now-------获取当前时间
4.9.其他模块
Calendar模块-----日历模块
uuid模块------------获取永不重复的字符串
dir(datetime)
[‘add’, ‘class’, ‘delattr’, ‘dir’, ‘doc’, ‘eq’, ‘format’, ‘ge’, ‘getattribute’, ‘gt’, ‘hash’, ‘init’, ‘init_subclass’, ‘le’, ‘lt’, ‘ne’, ‘new’, ‘radd’, ‘reduce’, ‘reduce_ex’, ‘repr’, ‘rsub’, ‘setattr’, ‘sizeof’, ‘str’, ‘sub’, ‘subclasshook’, ‘astimezone’, ‘combine’, ‘ctime’, ‘date’, ‘day’, ‘dst’, ‘fold’, ‘fromisocalendar’, ‘fromisoformat’, ‘fromordinal’, ‘fromtimestamp’, ‘hour’, ‘isocalendar’, ‘isoformat’, ‘isoweekday’, ‘max’, ‘microsecond’, ‘min’, ‘minute’, ‘month’, ‘now’, ‘replace’, ‘resolution’, ‘second’, ‘strftime’, ‘strptime’, ‘time’, ‘timestamp’, ‘timetuple’, ‘timetz’, ‘today’, ‘toordinal’, ‘tzinfo’, ‘tzname’, ‘utcfromtimestamp’, ‘utcnow’, ‘utcoffset’, ‘utctimetuple’, ‘weekday’, ‘year’]
uuid.uuid4().hex
>>> uuid.uuid4().hex
'd797c805e89641abbbe54f903399b474'
>>> uuid.uuid4().hex
'd8905e59492f437faa2c41168c8c7b52'
>>> uuid.uuid4().hex
'51735217895541d4a1cddbab31989b7e'
可用于加密盐值或文件名字