第七章 内置模块

目录

第七章 内置模块

7.1 math模块

7.2 random

7.3 os模块

7.4 os.path模块

7.5 sys模块

7.6 UUID模块

7.7 时间模块

7.7.1 time模块

7.7.2 datetime模块

7.7.3 calendar模块

7.8 加密模块

7.8.1 hashlib模块

7.8.2 hmac模块

第七章 内置模块

1、什么是模块?

import XXXX ----- XXXX就是一个模块 自己去定义的XX.py的文件本质上也是一个模块

2、模块的分类

根据创建者的角色可以进行分类:

系统的内置模块 (math random os os.path uuid .........)

第三方模块 ------- 使用之前需要自行的进行安装

在线安装 pip install 模块名称 -i 国内镜像源(清华大学 豆瓣)

离线安装 下载安装包 setup.py

自定义模块 ------ XXX.py

3、模块导入的问题

import 关键字进行模块的导入

import 模块的名称

import 模块的名称 as 别名

from 包或者模块 import 子模块

7.1 math模块

 >>> dir(math)
 Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
 NameError: name 'math' is not defined
 >>> import 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']

ceil ---- 天花板的意思 向上取整

floor ----- 向下取整

fabs ------ 求绝对值 等价于全局函数abs

fmod ---- 求模

pow ------ 幂次方

sqrt ------ 根号 开平方根

7.2 random

产生随机数

 >>> import random
 >>> 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']

randint ------ 产生的是一个范围内的随机数[a,b]

random ---- 产生的是[0,1) 之前的一个随机数

randrange ------ 产生的是一个范围内的随机数

choice ------表示的是在序列(有序 set是无序的)随机筛选一个元素

 >>> ls = [1,2,3,4,5,6,7,8,9,]
 >>> ls
 [1, 2, 3, 4, 5, 6, 7, 8, 9]
 >>> random.choice(ls)
 4
 >>> random.choice(ls)
 1
 >>> random.choice(ls)
 7
 >>> random.choice(ls)
 2
 >>> s = {1,2,3,4,5,6,7}
 >>> random.choice(s)
 Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "D:\SoftWare\python3.9\lib\random.py", line 346, in choice
     return seq[self._randbelow(len(seq))]
 TypeError: 'set' object is not subscriptable
 >>> random.randint(1,10)
 9
 >>> random.randint(1,10)
 1
 >>> random.randint(1,10)
 8
 >>> random.randint(1,10)
 6
 >>> random.randint(1,10)
 1
 >>> random.randint(1,10)
 10
 >>> random.random()
 0.6897423785904746
 >>> random.random()
 0.9053575998616402
 >>> random.random()
 0.02938124129562203
 >>> random.random()
 0.5407142439816497
 >>> random.random()
 0.9987733723015613
 >>> random.random()
 0.6238339698087764

需求:猜单词的小游戏 random模块 循环 切片

单词存储在某个容器里面

("python","hhshshsh","goods","position","difficult",.............)

 #猜单词小游戏
 import random
 WORDS = ("python","words","difficult","goods","position","math","java","easy")
 print("欢迎来到猜单词的游戏,请将乱序后的单词组成正确的单词")
 iscontinue = "Y"
 while iscontinue == "Y" or iscontinue == "y":
     words = random.choice(WORDS)
     # print(words)
     right = words
     #打乱顺序
     newwords = ""
     while words:
         postion = random.randrange(len(words))
         # print(postion)
         newwords += words[postion]
         # print(newwords)
         words = words[:postion] + words[(postion+1):]
     print("乱序后的单词是:",newwords)
     guess = input("请你猜单词:")
     # if guess == right:
     #     print("恭喜您,猜对了")
     # else:
     #     print("很抱歉,您猜错了!!!!")
     while guess != right or guess == "":
         print("很抱歉,您猜错了!!!!")
         guess = input("请你猜单词:")
     if guess == right:
         print("恭喜您,猜对了!!!!")
     iscontinue = input("请您选择是都继续(Y/N)")

7.3 os模块

用来操作系统文件

 Type "help", "copyright", "credits" or "license" for more information.
 >>> import os
 >>> dir(os)
 ['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']

chdir (path) -------- 表示的是修改当前的工作目录

curdir ------- 获取的是当前的目录 返回的是一个相对路径 os.path.abspath() ------ 获取的是绝对路径

 >>> os.curdir
 '.'
 >>> os.path.abspath(os.curdir)
 'C:\\Users\\WX'
 >>> os.chdir("C:\\")
 >>> os.path.abspath(os.curdir)
 'C:\\'

chmod ----- 修改权限,主要用于Linux

close ----- 关闭文件

cpu_count -------- 返回的是cpu核对应的线程数(2核4线程)

getcwd ---- 获取当前的路径,返回的是绝对路径,相当于linux中pwd

getpid ------- 获取的是当前进程的进程编号

getppid ------ 获取的当前进程的父进程的编号

kill ------ 通过进程编号杀死进程

linesep -------- 获取对应系统下的换行符

listdir ------- 返回的是对应目录下面的所有文件和文件夹(包含隐藏文件),返回的是列表的形式

makedirs -------- 创建目录(文件夹)支持多层创建

mkdir ------ 创建目录,单层创建

 >>> os.path.abspath(os.curdir)
 'C:\\'
 >>> os.makedirs("A//B//C//D")
 >>> os.mkdir("B")
 >>> os.mkdir("C//D//E")
 Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
 FileNotFoundError: [WinError 3] 系统找不到指定的路径。: 'C//D//E'

open ------ 打开文件,创建文件,等价于全局函数open()(IO流)

pathsep ------ 获取当前系统下环境变量的分隔符

sep --- 获取的是当前系统性路径的分隔符

remove(文件名称或者文件路径) -------- 删除文件

removedirs------- 删除目录,支持多层删除(递归删除)

 >>> os.pathsep
 ';'
 >>> os.sep
 '\\'
 >>> os.remove("C:\\A\\B\\C\\D\\a.txt")
 >>> os.removedirs("C:\\A\\B\\C")
 Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "D:\SoftWare\python3.9\lib\os.py", line 243, in removedirs
     rmdir(name)
 OSError: [WinError 145] 目录不是空的。: 'C:\\A\\B\\C'
 >>> os.removedirs("C:\\A\\B\\C\\D")

system ------ 执行一些终端命令

7.4 os.path模块

>>> import os
>>> dir(os.path)
[ '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
>>> dir(os.path)
[ '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']
>>> from os import path
>>> dir(path)
[ '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 as p
>>> dir(p)
['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']

abspath ----- 返回的相对路径所对应的绝对路径

altsep ------ 查看的python中的各种符号

basename ------- 返回的文件的名称 shell

dirname ------- 返回的是文件的路径

>>> p.basename("D:\\重大城科\\22级python0316\\第十天\\第十天.md")
'第十天.md'
>>> p.dirname("D:\\重大城科\\22级python0316\\第十天\\第十天.md")
'D:\\重大城科\\22级python0316\\第十天'

exists -------- 判断文件或者目录是否存在

isdir ------- 判断path是不是一个目录(文件夹)

isfile ------- 判断path是不是一个文件

isabs --------- 判断的是不是绝对路径

>>> p.isdir("D:\\重大城科\\22级python0316\\第十天\\第十天.md")
False
>>> p.isdir("D:\\重大城科\\22级python0316\\第十天")
True
>>> p.isfile("D:\\重大城科\\22级python0316\\第十天\\第十天.md")
True
>>> p.isfile("D:\\重大城科\\22级python0316\\第十天")
False
>>> p.isabs("D:\\重大城科\\22级python0316\\第十天")
True

getsize ------- 获取文件的大小,单位是字节

join ------ 拼接路径

>>> name = "a.txt"
>>> url = "A\\B\\C"
>>> url + "\\" + name
'A\\B\\C\\a.txt'
>>> path = url + "\\" + name
>>> path
'A\\B\\C\\a.txt'
>>> p.join(url,name)
'A\\B\\C\\a.txt'
>>> url + os.sep + name
'A\\B\\C\\a.txt'

sep ------- 路径的分隔符

>>> url + p.sep + name
'A\\B\\C\\a.txt'

split ----- 分隔路径

>>> p.split("D:\\重大城科\\22级python0316\\第十天\\第十天.md")
('D:\\重大城科\\22级python0316\\第十天', '第十天.md')

relpath ------ 返回的是真实的路径(绝对路径)相当于abspath()

需求:

结合os和os.path和函数的部分

给出一个路径,遍历这个路径下面的所有文件和文件夹,打印输出所有文件的路径(如果遇到的是文件输出文件的路径,如果遇到的是文件夹继续进入文件夹里面直到输出文件的路径)

import os
import os.path as p
#定义一个函数 
def scanner_file(url):
    #输出该路径下面所有的文件和文件夹
    files = os.listdir(url)
    # print(files)
    for f in files:
        # real_url =  url + "\\" + f
        # real_url = url + os.sep + f 
        real_url = p.join(url,f)
        # print(real_url)
        #判断这个路径是不是文件夹
        if p.isdir(real_url):
            scanner_file(real_url)
        elif p.isfile(real_url):
            print(p.abspath(real_url))
        else:
            print("其他情况!!!!")
            pass

scanner_file("D:\\重大城科\\22级python0316")

7.5 sys模块

>>> import sys
>>> dir(sys)
[ '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', 'last_traceback', 'last_type', 'last_value', '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']

api_version --------- 获取当前python的内部版本号

argv ------ 获取脚本参数,返回的是列表

copyright ------ 获取的python的版本信息

exit ------ 退出系统

getdefaultencoding -------- 获取的是默认的编码格式,python3中默认的编码格式是utf-8

getfilesystemencoding -------- 获取文件系统的编码格式,默认的也是uft-8

getrecursionlimit ------ 获取的是递归的限制层数

setrecursionlimit ------- 设置递归的限制层数(一般不要使用)

getrefcount -------- 获取的是对象的引用计数,指的是垃圾回收机制中的引用计数

补充:

python中的垃圾回收机制的原理:以引用计数为主,以标记清除和分代收集为辅

Java:以标记清除为主,以引用计数和分代收集为辅

>>> ls1 = [1,2,3,4,5]
>>> sys.getrefcount(ls1)
2
>>> x = ls1
>>> sys.getrefcount(ls1)
3
>>> y = ls1
>>> sys.getrefcount(ls1)
4
>>> z = ls1
>>> sys.getrefcount(ls1)
5
import os
import os.path as p
import sys
#定义一个函数 
def scanner_file(url):
    #输出该路径下面所有的文件和文件夹
    files = os.listdir(url)
    # print(files)
    for f in files:
        # real_url =  url + "\\" + f
        # real_url = url + os.sep + f 
        real_url = p.join(url,f)
        # print(real_url)
        #判断这个路径是不是文件夹
        if p.isdir(real_url):
            scanner_file(real_url)
        elif p.isfile(real_url):
            print(p.abspath(real_url))
        else:
            print("其他情况!!!!")
            pass

ls = sys.argv  #py demo01.py D:\\重大城科\\22级python0316 hhhh  hhhh
# print(ls) #["demo01.py","D:\\重大城科\\22级python0316","hhhh","hhhh"]
if len(ls) < 2:
    print("很抱歉,请输入脚本参数!!!!")
else:
    scanner_file(ls[1])

7.6 UUID模块

UUID ----- 一种技术,在文件上传、备份的时候经常使用

会产生一个永不重复的串

>>> import uuid
>>> dir(uuid)
['Enum', 'NAMESPACE_DNS', 'NAMESPACE_OID', 'NAMESPACE_URL', 'NAMESPACE_X500', 'RESERVED_FUTURE', 'RESERVED_MICROSOFT', 'RESERVED_NCS', 'RFC_4122', 'SafeUUID', 'UUID', '_AIX', '_GETTERS', '_LINUX', '_MAC_DELIM', '_MAC_OMITS_LEADING_ZEROES', '_OS_GETTERS', '_UuidCreate', '__author__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_arp_getnode', '_find_mac_near_keyword', '_find_mac_under_heading', '_generate_time_safe', '_get_command_stdout', '_has_uuid_generate_time_safe', '_ifconfig_getnode', '_ip_getnode', '_ipconfig_getnode', '_is_universal', '_lanscan_getnode', '_last_timestamp', '_load_system_functions', '_netbios_getnode', '_netstat_getnode', '_node', '_parse_mac', '_random_getnode', '_unix_getnode', '_uuid', '_windll_getnode', 'bytes_', 'getnode', 'int_', 'os', 'sys', 'uuid1', 'uuid3', 'uuid4', 'uuid5']
>>> uuid.uuid4()
UUID('0d8c5a61-c516-46eb-aa28-28f0df1dbdc2')
>>> uuid.uuid4()
UUID('eaab412f-06db-4ef7-ab09-859f275f05ba')
>>> uuid.uuid4().hex
'2695506b282745f28a6b9aba7a93ae35'
>>> uuid.uuid4().hex
'df6cb7bdf6ea4d92b83d35921e4b57c5'
>>> uuid.uuid4().hex
'528191cde9ca436b96f24d04f67cb511'
>>> uuid.uuid4().hex
'858254d9cbb449ee9fc3b0c3f3a23091'
>>> uuid.uuid4().hex
'37c2fa4f4731499a90b4d339c703d593'

7.7 时间模块

7.7.1 time模块
>>> import time
>>> dir(time)
['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']

asctime ----- 获取当前的时间

ctime ----- 获取当前的时间

>>> time.asctime()
'Sun May 12 16:51:11 2024'
>>> time.ctime()
'Sun May 12 16:51:42 2024'

localtime ------ 获取的是本地时间,返回的是一个对象,方便格式化

>>> ltime = time.localtime()
>>> ltime
time.struct_time(tm_year=2024, tm_mon=5, tm_mday=12, tm_hour=16, tm_min=53, tm_sec=47, tm_wday=6, tm_yday=133, tm_isdst=0)
>>> ltime.tm_year
2024
>>> print("%s-%s-%s %s:%s:%s"%(ltime.tm_year,ltime.tm_mon,ltime.tm_mday,ltime.tm_hour,ltime.tm_min,ltime.tm_sec))
2024-5-12 16:53:47

sleep ------ 休眠时间,单位是秒

time ------- 获取的是当前系统下时间戳,单位是秒,永不重复

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 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.
>>> time.strftime("%Y-%m-%d %H:%M:%S")
'2024-05-12 17:09:18'
>>> ss = time.strftime("%Y-%m-%d %H:%M:%S")
>>> ss
'2024-05-12 17:10:30'
>>> type(ss)
<class 'str'>

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 = "2025-5-20 17:03:30"
>>> s
'2025-5-20 17:03:30'
>>> type(s)
<class 'str'>
>>> time.strptime(s,"%Y-%m-%d %H:%M:%S")
time.struct_time(tm_year=2025, tm_mon=5, tm_mday=20, tm_hour=17, tm_min=3, tm_sec=30, tm_wday=1, tm_yday=140, tm_isdst=-1)
7.7.2 datetime模块

from datetime import datetime

>>> from datetime import datetime
>>> dir(datetime)
[ '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']
7.7.3 calendar模块

7.8 加密模块

加密算法的分类:

以算法是否可逆:可逆算法(是不是使用的是同一对密钥:对称加密(加密和解密的时候使用的是同一个密钥)、不对称加密(加密和解密的时候使用的同一对密钥))

不可逆算法(hash算法)特点:不可逆、结果是唯一的 MD5

7.8.1 hashlib模块

import hashlib

dir(hashlib)

>>> import hashlib
>>> dir(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举例(接收的数据一定是字节数据)

>>> hashlib.md5("123")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Unicode-objects must be encoded before hashing
>>> hashlib.md5("123".encode("utf-8"))
<md5 _hashlib.HASH object @ 0x0000028C59F0BB10>
>>> md5 = hashlib.md5("123".encode("utf-8"))
>>> md5
<md5 _hashlib.HASH object @ 0x0000028C59F0BF50>
>>> dir(md5)
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'block_size', 'copy', 'digest', 'digest_size', 'hexdigest', 'name', 'update']
>>> md5.hexdigest()
'202cb962ac59075b964b07152d234b70'
>>> md5 = hashlib.md5("123whgtbnn@@@@@@".encode("utf-8"))
>>> md5.hexdigest()
'50a46a3e6534a15d967740f1d1a0ec8a'

盐值混淆

>>> md5 = hashlib.md5("123".encode("utf-8"))
>>> md5.update("$$$%^&&&&GGGHHHH".encode("utf-8"))
>>> md5.hexdigest()
'033d9581694bd734ffeec1a6dc3d9768'
7.8.2 hmac模块

hmac也是一个哈希加密的模块

>>> import 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']

new -------- 三个参数 第一个参数是要加密的字符串 第二参数 盐值 第三个参数加密的方法

>>> md5 = hmac.new("12345".encode("utf-8"),"&&**(*…………*".encode("utf-8"),"md5")
>>> md5
<hmac.HMAC object at 0x0000028C5A5DD400>
>>> md5.hexdigest()
'ca1b1f199bf82b6456ee9b5a5032359b'

加密过程:首先使用了对称加密(密钥是盐值),之后再将加密后的数据进行了一次hsah加密(盐值混淆)

需求:

登录注册的页面(函数),注册的时候需要将用户的用户名和密码进行存储(容器),存储后的密码是加密后的密文

1、用户注册

2、用户登录

3、退出系统

 import sys
 import hashlib
 users = []
 salt = "^&**&^%$*HGF$&I^*OJNB"
 def password_md5(password):
     md5 = hashlib.md5(password.encode("utf-8"))
     md5.update(salt.encode("utf-8"))
     return md5.hexdigest()
 def main():
     print("~*"*20)
     print("1、用户注册")
     print("2、用户登录")
     print("3、退出系统")
     print("~*"*20)
     choice = input("请输入你要操作的选项:")
     return choice
 def register():
     username = input("请输入您的用户名:")
     password = input("请输入您的密码:")
     #验证一下数据是否符合要求
     if username == None or username.strip() == "" :
         print("用户名不能为空!!!!")
         return
     elif password == None or password.strip() == "" or len(password) < 3 :
         print("密码不能为空或者密码过短!!!!!")
         return
     #用户名已经存在的化怎么办?
     # for i in users:
     #     if i.get("username") == username:
     #         print("用户名已经存在")
     if exit_user(username):
         print("用户名已经存在!!!!!")
         return
     user = {}
     user["username"] = username
     # user["password"] = password
     user["password"] = password_md5(password)
     users.append(user)
     print(users)
 def  exit_user(username):
     for i in users:
         if i.get("username") == username:
             print("用户名已经存在")
             return True
     return False
 def login():
     username = input("请输入您的用户名:")
     password = input("请输入您的密码:")
     password = password_md5(password)
     if is_login(username,password):
         print("成功了")
         return
     else:
         print("用户名或者密码输入有误,请重新输入或者注册")
 def is_login(username,password):
     for i in users:
         if i.get("username") == username and i.get("password") == password:
             print("登录成功了!!!!")
             return True
     return False
 while True:
     choice = main()
     if choice == "1":
         print("用户注册")
         #注册本质是不是需要把用户的信息存储下来  数据库  IO  容器(字典+列表)
         register()
     elif choice == "2":
         print("用户登录")
         login()
     else:
         print("系统正常退出")
         sys.exit()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

璀云霄

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值