常用模块

常用的模块

一、时间模块

  • time.time()
'''
在python的三种时间表现形式:
    1.时间戳: 给电脑看的。
        - 自1970-01-01 00:00:00到当前时间,按秒计算,计算了多少秒。

    2.格式化时间(Format String): 给人看的
        - 返回的是时间的字符串 2002-01-11

    3.格式化时间对象(struct_time):
        - 返回的是一个元组, 元组中有9个值:
            9个值分别代表: 年、月、日、时、分、秒、一周中第几天,一年中的第几天,夏令时(了解)

时间模块
'''

#1、获取时间戳
import time
time.time()
print(time.time())
>>>1573885326.357931
  • time.strftime()获取格式化时间
#2、获取格式化时间
import time
time.strftime()
'''
     %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].
 '''
#获取年月日
 time.strftime('%Y-%m-%d')
 print(time.strftime('%Y-%m-%d'))
 >>>2019-11-16
#获取年月日时分秒
 time.strftime('%Y-%m-%d %H-%M-%S')
 print(time.strftime('%Y-%m-%d %H:%M:%S')) # %H:%M:%S也可以用%X来代替
>>>2019-11-16 14:29:21

  • struct_time()时间对象
import time
#3、获取时间对象
time.localtime()#通过这个获取一个时间对象
print(time.localtime())
>>>time.struct_time(tm_year=2019, tm_mon=11, tm_mday=16, tm_hour=14,
>>>tm_min=31, tm_sec=50, tm_wday=5, tm_yday=320, tm_isdst=0)
time_obj = time.localtime()#是一个容器,可以用.方法
print(time_obj.tm_year)
>>>2019
print(time_obj.tm_mon)
>>>11
print(time_obj.tm_mday)
>>>16


res = time.localtime()
time.sleep(5)#模拟以前的时间和现在的现在的时间的一个延迟操作

#获取当前时间的格式化时间
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
>>>2019-11-16 14:45:13

#将时间对象转换为格式化时间
print(time.strftime('%Y-%m-%d %H:%M:%S', res))#可以通过这种操作格式化之前的时间
>>>2019-11-16 14:45:08

#将字符串格式的时间转换成时间对象
res = time.strptime('2019-12-12', '%Y-%m-%d')
print(res)
>>>time.struct_time(tm_year=2019, tm_mon=12, tm_mday=12, tm_hour=0, tm_min=0, tm_sec=0,
tm_wday=3, tm_yday=346, tm_isdst=-1)

  • datetime()基于time模块的更高级的模块
import datetime

#获取当前年月日(*******)
datetime.date.today()
print(datetime.date.today())
#>>>2019-11-16

#获取当前年月日时分秒(*******)
datetime.datetime.today()
print(datetime.datetime.today())
#>>>2019-11-16 15:08:58.116342

time_obj = datetime.datetime.today()
print(type(time_obj))
#>>><class 'datetime.datetime'>

print(time_obj.year)
#>>>2019
print(time_obj.month)
#>>>11
print(time_obj.day)
#>>>16

#UTC从0开始计算周一
print(time_obj.weekday())
#>>>5所以是6变成5

#ISO
print(time_obj.isoweekday())
#>>>6


#北京时间(*******)
print(datetime.datetime.now())
#>>>2019-11-16 15:19:14.398864

#格林威治时间(与北京时间差8个小时)
print(datetime.datetime.utcnow())
#>>>2019-11-16 07:20:15.837757


'''
日期/时间的计算 (*******)
    日期时间 = 日期时间 “+” or “-” 时间对象
    时间对象 = 日期时间 “+” or “-” 日期时间
'''

#日期时间
current_time = datetime.datetime.now()
print(current_time)
#>>>2019-11-16 15:29:59.851922


#时间对象
#获取7天后的时间
time_obj = datetime.timedelta(days=7)
print(time_obj)
#>>>7 days, 0:00:00


#日期时间
later_time = current_time + time_obj
print(later_time)
#>>>2019-11-23 15:29:59.851922

# 时间对象 = 日期时间 “+” or “-” 日期时间
time_obj = later_time - current_time
print(time_obj)
#>>>7 days, 0:00:00


  • random随机模块
import random

#获取任意整数的玩法,范围自己设置
random.randint(1, 10)
print(random.randint(1, 10))
#>>>4
#>>>2
#>>>7

#获取0-1之间的任意小数
random.random()
print(random.random())
#>>>0.1955805646689478
#>>>0.2569278638423781

#洗牌将可迭代对象中的值重新排序
list1 = ['yafeng', 'sean', 'tank', 'egon']
random.shuffle(list1)
print(list1)
#>>>['tank', 'sean', 'yafeng', 'egon']
#>>>['tank', 'sean', 'egon', 'yafeng']


#随机获取可迭代对象中的某一个值
random.choice(list1)
print(random.choice(list1))
#>>>tank


#需求制造一个随机验证码

'''
需求: 
    大小写字母、数字组合而成
    组合5位数的随机验证码

前置技术:
    - chr(97)  # 可以将ASCII表中值转换成对应的字符97对应a
    # print(chr(101))
    - random.choice
'''

#比如随机获取四位数的验证码
def get_code(n):
    code = ''
    # 每次循环只从大小写字母、数字中取出一个字符
    for line in range(4):#这里要把4变成n就是任意长度字符串

        #随机获取一个小写字母(ascll对应的值是97-122)
        res1 = random.randint(97, 122)
        low_str = chr(res1)

        #随机获取一个大写字母(ascll对应的是65-90)
        res2 = random.randint(65, 90)
        upper_str = chr(res2)

        #随机获取一个数字
        number = str(random.randint(0, 9))

        code_list = [low_str, upper_str, number]
        random_code = random.choice(code_list)

        code += random_code

    return code

code = get_code(4)
print(code)
print(len(code))
#>>>ghj7
#>>>4

  • os模块
'''
os与操作系统交互的模块
'''

import os
import time

#需求获取当前项目根目录
os.path.dirname(__file__)
print(os.path.dirname(__file__))
#>>>D:/python的pycharm/正式课/day15

#需求当前文件上一级的根目录
DAY15_PATH = os.path.dirname(__file__)
BASE_PATH = os.path.dirname(DAY15_PATH)
print(BASE_PATH)
#>>>D:/python的pycharm/正式课

#路径的拼接:拼接文件的'绝对路径'
TEST_PATH = os.path.join(DAY15_PATH, 'yafeng666.txt')
print(TEST_PATH)
#>>>D:/python的pycharm/正式课/day15yafeng666.txt注意最后一个是


# 判断“文件/文件夹”是否存在:若文件存在返回True,若不存在返回False
print(os.path.exists(TEST_PATH))  #True
print(os.path.exists(os.path.exists(DAY15_PATH)))   #True


#判断文件夹是否存在os.exists
#先删除'yafeng666.txt'
print(os.path.exists(TEST_PATH))     #False
#>>>False

print(os.path.exists(os.path.exists(DAY15_PATH)))   #True


#创建文件夹os.mkdir
DIR_PATH = os.path.join(DAY15_PATH, '各位老湿写真集')
# os.mkdir(DIR_PATH)

# time.sleep(3)

#删除文件夹只能删除'空的文件夹'os.rmdir
# os.rmdir(DIR_PATH)#注意要写把创建文件注释以后才可以执行删除文件的操作,
# 不可以同时既创建,又删除


#获取某个文件夹中所有文件的名字
teacher_list = os.listdir(r'D:python的pycharm正式课day15各位老湿写真集')
print(teacher_list)
#>>>['egon老湿的写真集', 'Jason老湿的写真集', 'Sean老湿的写真集', 'tank老湿的写真集']

# enumerate(可迭代对象) ---> 得到一个对象,对象有一个个的元组(索引, 元素)
res = enumerate(teacher_list)#一个对象
print(list(res))

# 让用户选择文件
while True:

    # 1.打印所有老师的作品
    for index, name in enumerate(teacher_list):
        print(f'编号:{index},文件名:{name}')

    choice = input('请选择想看老湿的作品---->(头条影片:Jason写真集) 编号:').strip()

    # 2.限制用户必须输入数字,数字的范围必须在编号内
    # 若不是数字,则重新选择
    if not choice.isdigit():
        print('必须输入数字')
        continue
    # 若是数字,往下走判断是否在编号范围内
    choice = int(choice)

    # 判断如果不在列表范围内,则重新选择
    if choice not in range(len(teacher_list)):
        print('编号范围错误!')
        continue

    file_name = teacher_list[choice]

    teacher_path = os.path.join(r'D:python的pycharm正式课day15各位老湿写真集', file_name)

    print(teacher_path)

    with open(teacher_path, 'r', encoding='utf-8') as f:
        print(f.read())

#>>>['egon老湿的写真集', 'Jason老湿的写真集', 'Sean老湿的写真集', 'tank老湿的写真集']
# [(0, 'egon老湿的写真集'), (1, 'Jason老湿的写真集'), (2, 'Sean老湿的写真集'), (3, 'tank老湿的写真集')]
# 编号:0,文件名:egon老湿的写真集
# 编号:1,文件名:Jason老湿的写真集
# 编号:2,文件名:Sean老湿的写真集
# 编号:3,文件名:tank老湿的写真集
# 请选择想看老湿的作品---->(头条影片:Jason写真集) 编号:
# 请选择想看老湿的作品---->(头条影片:Jason写真集) 编号:2
# D:python的pycharm正式课day15各位老湿写真集Sean老湿的写真集
# 3333(假设这个内容就是写真集)


  • sys模块
import sys
import os

#获取当前python解释器的环境变量路径
sys.path
print(sys.path)

#将当前项目添加到环境变量中去
BASE_PATH = os.path.dirname(os.path.dirname(__file__))
sys.path.append(BASE_PATH)

#获取cmd终端的命令行 python3 py文件 用户名 密码
print(sys.argv) #返回的是列表[]
  • hashlib
'''   - sha_256(了解)
hashlib是一个加密模块:
    内置了很多算法
    - MD5(*******): 不可解密的算法(2018年以前)

    摘要算法:
        - 摘要是从某个内容中获取的加密字符串
        - 摘要一样,内容就一定一样: 保证唯一性

        - 密文密码就是一个摘要
'''

import hashlib

md5_obj = hashlib.md5()
print(type(md5_obj))
#>>><class '_hashlib.HASH'>
str1 = '1234'
#****update中一定要传入bytes类型*****
md5_obj.update(str1.encode('utf-8'))#编码

#得到一个加密后的字符串
res = md5_obj.hexdigest()
print(res)
#>>>81dc9bdb52d04dc20036dbd8313ed055这就是加密后的'1234'

#注意以上操作撞库有可能会破解真实密码

#所以为了防止撞库的可能,要加盐

import hashlib

def pwd_md5(pwd):
    md5_obj = hashlib.md5()

    #'666'
    # ****update中一定要传入bytes类型*****
    md5_obj.update(pwd.encode('utf-8'))

    #创造盐
    sal = '亚峰真的帅'
    #加盐
    md5_obj.update(sal.encode('utf-8'))

    #得到一个加密后的字符串
    res = md5_obj.hexdigest()

    return res

# user_str1 = f'yafeng:666'
#
# user_str2 =f'yafeng:{res}'
#
# with open('user.txt', 'w', encoding='utf-8')as f:
#     f.write(user_str2)

#模拟用户登录操作
#获取文件中的文件名与密码
with open('user.txt', 'r', encoding='utf-8')as f:
    user_str = f.read()

file_user, file_pwd = user_str.split(':')

#用户输入用户名与密码
username = input('请输入您的用户名').strip()
password = input('请输入您的密码').strip()
res = pwd_md5(password)
print(res)
print(file_pwd)
#校验用户名与密码是否一致
if username == file_user and file_pwd == res:
    print('登录成功')
else:
    print('登录失败')


原文地址:https://www.cnblogs.com/yafeng666/p/11873085.html