table of Contents
Introduction and use of built-in module
A, time module
Of the three forms of time Python:
- Timestamp: to look at the computer
- From 1970-01-01 00:00:00 to the current time, in seconds calculation, calculate how many seconds
- Formatting time (Format String): posters
- Returns the string time 2019-11-16
- Time Object Format (struct_time):
- It returns a tuple, 9-tuple values:
- They represent: year, month, day, hour, minute, second, day of the week, the first day of the year, daylight saving time
- It returns a tuple, 9-tuple values:
import time
Time stamp calculation used to obtain
print(time.time())
- Acquisition time format, use format and save the user time splicing
time.strftime('%Y-%m-%d %H:%M:%S')
Minutes acquiring date- % Y in
% m dated
% d day
% H when
% M minutes
% S seconds
Gets the current time format
print(time.strftime('%Y-%m-%d')) # 年月日 print(time.strftime('%H-%M-%S')) # 时分秒
Gain practical objects
# 获取时间对象 print(time.localtime()) print(type(time.localtime())) time_obj = time.localtime() print(time_obj.tm_year) print(time_obj.tm_hour)
res = time.localtime()
# 获取当前时间的格式化时间
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
# 将时间对象转为格式化时间
print(time.strftime('%Y-%m-%d %H:%M:%S', res))
# 将字符串格式的时间转化为时间对象
res = time.strptime('2019-01-01', '%Y-%m-%d')
print(res)
2019-11-16 15:23:17
2019-11-16 15:23:17
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)
Two, datetime module
import datetime
# 获取当前年月日
print(datetime.date.today())
2019-11-16
# 获取当年年月日时分秒
print(datetime.datetime.today())
2019-11-16 15:26:37.224224
time_obj = datetime.datetime.today()
print(time_obj.year)
print(time_obj.month)
print(time_obj.day)
2019
11
16
# 从索引0开始计算周一
# UTC
print(time_obj.weekday()) # 0-6
# ISO
print(time_obj.isoweekday()) # 1-7
UTC time zone:
Beijing
print(datetime.datetime.now())
Greenwich
print(datetime.datetime.utcnow())
Calculating date / time
Date Date Time Time = "+" or "-" Time Object
Target = Date Time Time "+" or "-" Date Time
# 日期时间
current_time = datetime.datetime.now()
print(current_time)
# 获取7天时间
time_obj = datetime.timedelta(days=7)
print(time_obj)
# 获取当前时间 7天后的时间
later_time = current_time + time_obj
print(later_time)
time_new_obj = later_time - time_obj
print(time_new_obj)
Three, random module
import random
Obtaining a random arbitrary integer 1-9
res = random.randint(1, 9)
print(res)
Default get any decimals between 0-1
res1 = random.random()
print(res1)
The value of the iteration is performed in the object may be out of order (shuffling)
l1 = [5, 4, 9, 8, 6, 7, 3, 1, 2, 0]
random.shuffle(l1)
print(l1)
Gets a value may be a random iteration object
l1 = [5, 4, 9, 8, 6, 7, 3, 1, 2, 0]
print(random.choice(l1))
Exercise
Random codes
"""
需求:
大小写字母、数字组合而成
组合5位数的随机验证码
前置技术:
chr() 可以将ASCII码表中值转换成对应的字符
"""
def get_code(n):
code = ''
for line in range(n):
# 随机获取一个小写字母
res1 = random.randint(97, 122)
lower_str = chr(res1)
# 随机获取一个大写字母
res2 = random.randint(65, 90)
upper_str = chr(res2)
# 随机获取一个数字
number = str(random.randint(0, 9))
code_list = [lower_str, upper_str, number]
random_code = random.choice(code_list)
code += random_code
return code
code = get_code(4)
print(code)
Four, OS module
import os
os is interacting with the operating system modules
Gets the parent directory of the current file
DAY15_PATH = os.path.dirname(__file__)
print(DAY15_PATH)
E:/python_file/day 15
The root directory of the project, the path associated values are in "constant"
BASE_PATH = os.path.dirname(DAY15_PATH)
print(BASE_PATH)
E:/python_file
Mosaic path: file splice "absolute path"
TEST_PATH = os.path.join(DAY15_PATH,'合集')
print(TEST_PATH)
E:/python_file/day 15\合集
Judgment "File / Folder" exists: If the file exists returns True, if there returns False
print(os.path.exists(TEST_PATH))
print(os.path.exists(DAY15_PATH))
False
True
Judgment "folder" exists
print(os.path.isdir(TEST_PATH))
print(os.path.isdir(DAY15_PATH))
False
True
Judgment "File" exists
print(os.path.isfile(TEST_PATH))
print(os.path.isfile(DAY15_PATH))
False
True
Create a folder
DIR_PATH = os.path.join(DAY15_PATH,'合集')
os.mkdir(DIR_PATH)
Delete the folder
os.rmdir(DIR_PATH)
Get the name of a folder, all files
# 获取某个文件夹下所有文件的名字,然后装进一个列表中
list1 = os.listdir('E:\python_file\day 15')
print(list1)
['01 time模块.py', '02 datetime模块.py', '03 random模块.py', '04 os模块.py', '05 sys模块.py', '06 hashlib模块.py', 'sys_test.py', 'test(day 15).py', '课堂笔记']
enumerate (iterables) ---> to give an object, the object has one tuple (index elements)
res = enumerate(list1)
print(list(res))
[(0, '01 time模块.py'), (1, '02 datetime模块.py'), (2, '03 random模块.py'), (3, '04 os模块.py'), (4, '05 sys模块.py'), (5, '06 hashlib模块.py'), (6, 'sys_test.py'), (7, 'test(day 15).py'), (8, '课堂笔记')]
Let the user select a file
list1 = os.listdir('E:\python_file\day 15')
res = enumerate(list1)
print(list(res))
# 让用户选择文件
while True:
for index, file in enumerate(list1):
print(f'编号{index} 文件名{file}')
choice = input('请选择需要的文件编号:').strip()
if not choice.isdigit():
print('请输入数字')
continue
choice = int(choice)
if choice not in range(len(list1)):
print('编号范围出错')
continue
file_name = list1[choice]
list1_path = os.path.join('E:\python_file\day 15', file_name)
print(list1_path)
with open(list1_path, 'r', encoding='utf-8')as f:
print(f.read())
Five, sys module
import sys
Gets the path environment variable current Python interpreter
print(sys.path)
Add the environment variable to the current project
BASE_PATH = os.path.dirname(os.path.dirname(__file__))
sys.path.append(BASE_PATH)
Get cmd terminal command line Python py file in the user name and password
print(sys.argv)
Six, hashlib module
import hashlib
It is a cryptographic module hashlib
It built a lot of algorithms
- MD5: algorithm undecipherable (2018)
- Digest Algorithm
- The digest is encrypted string obtained from a content
- As a summary, it will be content as: guaranteed to be unique
- Ciphertext password is a summary
md5_obj = hashlib.md5()
print(type(md5_obj))
str1 = '1234'
# update中一定要传入bytes类型数据
md5_obj.update(str1.encode('utf-8'))
# 得到一个加密后的字符串
res = md5_obj.hexdigest()
print(res)
<class '_hashlib.HASH'>
81dc9bdb52d04dc20036dbd8313ed055
The above operation is likely to hit the library crack password true
To prevent the hit library problem: salt
def pwd_md5(pwd):
md5_obj = hashlib.md5()
str1 = pwd
# update 中一定要传入bytes类型数据
md5_obj.update(str1.encode('utf-8'))
# 创造盐
sal = '我套你猴子'
# 加盐
md5_obj.update(sal.encode('utf-8'))
# 得到一个加密后的字符串
res = md5_obj.hexdigest()
return res
res = pwd_md5('1234')
user_str1 = f'yang:1234'
user_str2 = f'yang:{res}'
with open('user_info.txt', 'w', encoding='utf-8')as f:
f.write(user_str2)
Analog user login feature
# 获取文件中的用户名密码
with open('user_info.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('登录失败')