time, datatime, random, os, sys, hashlib module

time module

File naming convention: You can not name a module directly to the file name, for example: time.py

Three forms in python:

1. Timestamp: to look at the computer

2. Time Format (Format String) gives see

Returns the string time 2002-01-11

Time Object Format (struct_time)

- returns a tuple, 9-tuple values:

9 represents the values: year, month, day, hour, day of the week, daylight saving time

Time Module:

import time


# 1.获取时间戳   计算时间的时候使用

print(time.time())

# 2.获取格式化时间 拼接用户时间格式并保存使用

# 获取年月日

print(time.strftime('%Y-%m-%d'))

# 获取年月日时分秒

print(time.strftime('%Y-%m-%d %H-%M-%S'))

# %X =%H-%M-%S

print(time.strftime('%Y-%m-%d %X'))

# 获取年月

print(time.strftime('%Y/%m'))



1573885838.594383
2019-11-16
2019-11-16 14-30-38
2019-11-16 14:30:38
2019/11

# 3.获取时间对象
print(time.localtime())
print(type(time.localtime()))
time_obj = time.localtime()
print(time_obj.tm_yday)
print(time_obj.tm_year)
print(time_obj.tm_hour)


time.struct_time(tm_year=2019, tm_mon=11, tm_mday=16, tm_hour=14, tm_min=40, tm_sec=23, tm_wday=5, tm_yday=320, tm_isdst=0)
<class 'time.struct_time'>
320
2019
14
res = time.localtime()
time.sleep(5)

# 获取当前哥前时间的格式化时间
print(time.strftime('%Y-%m-%d %X', time.localtime()))
# 将时间对象转换为格式化时间
print(time.strftime('%Y-%m-%d %X', res))
# 将字符串格式的时间转换为时间对象
res = time.strptime('2019-01-01', '%Y-%m-%d')
print(res)


2019-11-16 14:46:34
2019-11-16 14:46:29
time.struct_time(tm_year=2019, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=1, tm_isdst=-1)

datetime module

import  datetime
# 获取当前年月
print(datetime.date.today())
# 获取当前年月日时分秒
print(datetime.datetime.today())
time_obj = datetime.datetime.today()
print(type(time_obj))
print(time_obj.year)
print(time_obj.month)
print(time_obj.day)

# UTC
print(time_obj.weekday())   # 0-6
# ISO
print(time_obj.isoweekday())    # 1-7

# UTC时区
# 北京时区
print(datetime.datetime.now())
# 格林威治
print(datetime.datetime.utcnow())

    
5
6
2019-11-16 15:00:43.409280
2019-11-16 07:00:43.409280

Calculating date / time

Date Date Time = Time + or - Time Object

Object Time = Time + or- Date Date Time

# 日期时间:
current_time = datetime.datetime.now()
print(current_time)

# 时间对象
# 获取七天时间
time_obj = datetime.timedelta(days=7)
print(time_obj)

# 获取当前时间七天后的时间
# 日期时间 =  日期时间 +or- 时间对象
late_time = current_time + time_obj
print(late_time)

# 时间对象 = 日期时间  + or- 日期时间
time_new_obj = late_time-current_time
print(time_new_obj)


2019-11-16 15:16:06.708308
7 days, 0:00:00
2019-11-23 15:16:06.708308
7 days, 0:00:00

random module

import random

# 随机获取1-9中的任意的整数
res = random.randint(1, 9)
print(res)
# 默认获取0-1之间任意小数
res2 = random.random()
print(res2)
# 洗牌
# 将可迭代对象中的值进行乱序(只能是集合)
my_list = [1, 2, 3, 4]
# print(random.shuffle(my_list))
random.shuffle(my_list)
print(my_list)
# 随机获取可迭代对象中的某一个值
list1 = [1, 2, 3, 4, 5]
print(random.choice(list1))

6
0.32282242064458144
[1, 2, 4, 3]
5

Demand: random codes
' ''
requirements:
uppercase and lowercase letters, numbers, a combination of
a combination of 5-digit random codes

Front Technology:

chr (97) # can be converted to the corresponding value of the ASCII table character

print(chr(101))

random.choice
'''

# 随机位数的验证码
def get_code(num):
    code = ''
    # 每次循环只从大小写字母,数字中取出一个字符
    for line in range(num):
        # 先随机获取一个小写字母
        res1 = random.randint(97, 122)

        lower_str = chr(res1)

        # 随机获取一个大写字母
        res2 = random.randint(65, 90)

        upper_str = chr(res2)

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

        number = str(res3)

        code_list = [lower_str, upper_str, number]

        random_code = random.choice(code_list)

        code += random_code

    return code


code = get_code(10)
print(code)


MI1If73hAK

os module

os module interacts with the operating system

import os

# 需求:获取当前项目根目录

# 获取当前文件中的上一级目录
DAY15_PATH = os.path.dirname(__file__)
print(DAY15_PATH)

# 项目的根目录,路径相关的值都用‘常量’   ps
# BASE_PATH = os.path.dirname(DAY15_PATH)
# print(BASE_PATH)
BASE_PATH = os.path.dirname(os.path.dirname(__file__))
print(BASE_PATH)


# 路径的拼接: 拼接文件   ‘绝对路径’
TEST_PATH = os.path.join(DAY15_PATH, '大帅的写真集.txt')
print(TEST_PATH)

# 判断‘文件/文件夹是否存在: 若文件存在则返回True,若不存在则返回False’
print(os.path.exists(TEST_PATH))
print(os.path.exists(DAY15_PATH))
print(os.path.exists(r'F:\python_work\python_oldboyedu_learn\day15\os模块.py'))

# 单独判断‘文件夹’是否存在,只能判断‘文件夹’,没法判断‘文件’
print(os.path.isdir(DAY15_PATH))
print(os.path.isdir(TEST_PATH))
print(os.path.isdir(r'F:\python_work\python_oldboyedu_learn\day15\os模块.py'))

# 创建文件夹
DIR_PATH = os.path.join(r'F:\python_work\python_oldboyedu_learn\day15', '大帅的写真集')
# os.mkdir(DIR_PATH)

# 删除文件夹:只能删除‘空的文件夹’
# os.rmdir(DIR_PATH)

# 获取某个文件夹中所有文件的名字
DSB_list = os.listdir(r'F:\python_work\python_oldboyedu_learn\day15\大帅的写真集')
print(DSB_list)

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

# 需求:打印所有的作品,让用户自行选择编号,讲结果打印出来
while True:
    # 打印出所有的编号文件
    for index, name in enumerate(DSB_list):
        print(f'编号:{index} 文件名:{name}')
        # 让用户选择编号
    choice = input('请选择想看的作品 选择编号:').strip()
    # 作出判断,限定用户必须输入的是数字,数字的范围要在编号范围内
    if not choice.isdigit():
        print('您必须输入数字')
        continue

    choice = int(choice)
    if choice not in range(len(DSB_list)):
        print('编号范围错误!')
        continue

    file_name = DSB_list[choice]
    DSB_path = os.path.join(r'F:\python_work\python_oldboyedu_learn\day15\大帅的写真集', file_name)

    with open(DSB_path, 'r', encoding='utf-8') as f:
        print(f.read())
        break
        
编号:0 文件名:__init__.py
编号:1 文件名:唐嫣写真集
编号:2 文件名:唐艺昕写真集.txt
编号:3 文件名:张歆艺写真集
请选择想看的作品 选择编号:2
唐艺昕大宝贝
超爱唐艺昕
唐艺昕真妹妹        
        

sys module

import sys
import os

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

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

# 获取cmd终端的命令行 python3 py文件 用户名 密码
print(sys.argv)  # 返回的是列表




['F:\\python_work\\python_oldboyedu_learn\\day15', 'F:\\python_work\\python_oldboyedu_learn', 'F:\\PyCharm 2019.2.3\\helpers\\pycharm_display', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\DLLs', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\lib', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages', 'F:\\PyCharm 2019.2.3\\helpers\\pycharm_matplotlib_backend']
['F:\\python_work\\python_oldboyedu_learn\\day15', 'F:\\python_work\\python_oldboyedu_learn', 'F:\\PyCharm 2019.2.3\\helpers\\pycharm_display', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\DLLs', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\lib', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages', 'F:\\PyCharm 2019.2.3\\helpers\\pycharm_matplotlib_backend', 'F:/python_work/python_oldboyedu_learn']
['F:/python_work/python_oldbolibyedu_learn/day15/sys模块.py']

hashlib module

hashlib is a cryptographic module:

It built a lot of algorithms

-md5: algorithm undecipherable (2018)

Digest Algorithm:

- Abstract encrypted string is obtained from a content

- Summary of the same, it will be content as: guaranteed to be unique

- encrypted passwords is a summary

import hashlib

md5_obj = hashlib.md5()
# print(type(md5_obj))
# print(md5_obj)
str1 = '1234'
# update中一定要传入bytes类型数据
md5_obj.update(str1.encode('utf-8'))

res = md5_obj.hexdigest()
print(res)

81dc9bdb52d04dc20036dbd8313ed055
# 以上操作撞库有可能会破解真实密码
# 防止撞库的问题:加盐

import hashlib


def pwd_md5(pwd):
    md5_obj = hashlib.md5()
    str1 = pwd
    md5_obj.update(str1.encode('utf-8'))

    # 创造盐

    sal = '唐艺昕我超级喜欢你哦'
    md5_obj.update(sal.encode('utf-8'))

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


# 模拟用户登录操作

# 获取文件中的用户名和密码
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()

# 校验用户名与密码是否一致
if username == file_user and file_pwd == pwd_md5(password):
    print('登录成功!')
else:
    print('登录失败!')
    if username != file_user:
        print('用户名不正确!')
    if file_pwd != pwd_md5(password):
        print('密码不正确!')
        
user.txt中的密码为:godlover:0291433999dba37a6e76e88802246fd8('1234'+'唐艺昕我超级喜欢你哦')


请输入用户名:godlover
请输入密码:1234
登录成功!

请输入用户名:godlover
请输入密码:123456
登录失败!
密码不正确

请输入用户名:godlover12
请输入密码:1234
登录失败!
用户名不正确!

请输入用户名:godloverwq
请输入密码:45456
登录失败!
用户名不正确!
密码不正确!

Guess you like

Origin www.cnblogs.com/godlover/p/11872972.html