time模块
time.sleep(n) : 休息n秒
time.time():返回一个从epoch到现在的秒数,epoch:start of time
import time
# 计算时间消耗
print(time.time(), type(time.time()))
# 1652579195.387747 <class 'float'>
time.time()可以用来计算一个程序执行所消耗的时间
# 开始时间
start = time.time()
# dosth (程序)
# 结束时间
end = time.time()
# 花费的时间
cost = end - start
time.ctime():获取当前时间字符串
# 获取当前时间(指定时间戳)的字符串
print(time.ctime(), type(time.ctime()))
# Sun May 15 09:51:54 2022 <class 'str'>
time.gmtime(n): 将当前时间戳转化为时间结构体(秒数 -> 时间结构体(0时区))
end = time.time()
# 将时间戳转化为时间结构体(元组)
# 0时区的时间
current = time.gmtime(end)
print(current, type(current))
# time.struct_time(tm_year=2022, tm_mon=5, tm_mday=15, tm_hour=1, tm_min=55, tm_sec=7, tm_wday=6, tm_yday=135, tm_isdst=0) <class 'time.struct_time'>
print(current.tm_year, current.tm_yday)
# 2022 135
current = time.gmtime(0) # 开始时间的结构体时间
print(current, type(current))
# time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0) <class 'time.struct_time'>
time.localtime(): 将时间戳转化为结构体时间
# time.localtime() 将时间戳转化为结构体时间
# 本地时间
current = time.localtime(end)
print(current, type(current))
# time.struct_time(tm_year=2022, tm_mon=5, tm_mday=15, tm_hour=9, tm_min=58, tm_sec=58, tm_wday=6, tm_yday=135, tm_isdst=0) <class 'time.struct_time'>
datetime模块
获取datetime模块的路径
print(datetime.__file__)
# D:\anaconda3\envs\python3.7\lib\datetime.py
datetime.datetime => 日期时间
# 获取今天的日期时间
now = datetime.datetime.now()
print(now, type(now))
# 2022-05-15 10:05:31.378419 <class 'datetime.datetime'>
print(now.year)
# 2022
datetime.date(类) =》日期
# 获取今天的日期
today = datetime.date.today()
print(today, type(today))
# 2022-05-15 <class 'datetime.date'>
print(today.year)
# 2022
datetime类型之间可以相减,获得timedelta(Δt)
import datetime
import time
now = datetime.datetime.now()
time.sleep(1)
now2 = datetime.datetime.now()
result = now2 - now
print(result, type(result))
# 0:00:01.002496 <class 'datetime.timedelta'>
计算n天前的日期
result = datetime.date.today() + datetime.timedelta(days=-n)
# 计算三天前的日期
today = datetime.date.today()
result = today + datetime.timedelta(days=-3)
print(result)
# 2022-05-12
today = datetime.datetime.now()
# 计算三天前的日期
result = today + datetime.timedelta(days=-3)
print(result)
# 2022-05-12 10:48:16.842966
# 计算一周前的日期
result = today + datetime.timedelta(weeks=-1)
print(result)
# 2022-05-08
# 计算10天后的日期
result = today + datetime.timedelta(days=10)
print(result)
# 2022-05-25
isinstance: 判断对象是否是指定类型
q = time.localtime()
print(q)
# time.struct_time(tm_year=2022, tm_mon=5, tm_mday=15, tm_hour=10, tm_min=18, tm_sec=41, tm_wday=6, tm_yday=135, tm_isdst=0)
# 判断q是不是元组类型
print(isinstance(q, tuple))
# True
结构体时间是一个元组的格式
数据格式及转换
格式化字符串
%Y 年
%m 月
%d 日
%H 时
%M 分
%S 秒
1、time.strftime(字符串的格式,时间结构体或元组):时间结构体或元组 -> 字符串
print(time.strftime("%Y/%m/%d", time.localtime()))
# 2022/05/15
print(time.strftime("%Y-%m-%d %H:%M:%S"), time.localtime())
# 2022-05-15 10:22:27
print(time.strftime("%Y/%m/%d %H:%M:%S", (2019, 1, 29, 15, 15, 23, 45, 21, 19)))
# 2019/01/29 15:15:23
2、time.strptime(要转换的字符串,字符串的格式):时间字符串 -> 返回时间结构体
print(time.strptime("2018/01/29 15:14:39", "%Y/%m/%d %H:%M:%S"))
# time.struct_time(tm_year=2018, tm_mon=1, tm_mday=29, tm_hour=15, tm_min=14, tm_sec=39, tm_wday=0, tm_yday=29, tm_isdst=-1)
print(time.strptime("20220515", "%Y%m%d"))
# time.struct_time(tm_year=2022, tm_mon=5, tm_mday=15, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=135, tm_isdst=-1)
3、将当前时间戳转化为元组
now = time.time()
print(now)
# 1652670527.4191196
print(time.localtime(now))
# time.struct_time(tm_year=2022, tm_mon=5, tm_mday=16, tm_hour=11, tm_min=8, tm_sec=47, tm_wday=0, tm_yday=136, tm_isdst=0)
json模块
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,它是JavaScript的子集,易于人阅读和编写。
前端和后端进行数据交互,其实就是JS和Python进行数据交互。
# json => 轻量级数据交换格式 => 字符串
# 不同语言之间数据交换
# list, str, dict =>
# js / java / go / php ......
# 前端 <= json => 后端
# 后端 <= json => 后端
python数据类型与json数据类型的映射关系
json中常用的方法
使用
import json
info = {
"name": "cali",
"score": 100,
"test0": False,
'test1': None
}
# 将python对象转为json
result = json.dumps(info)
print(result, type(result))
# {"name": "cali", "score": 100, "test0": false, "test1": null} <class 'str'>
# 将json对象转为python
result2 = json.loads(result)
print(result2, type(result2))
# {'name': 'cali', 'score': 100, 'test0': False, 'test1': None} <class 'dict'>
info = ["name", "cali", "score", 100, "test0", False, 'test1', None]
result = json.dumps(info)
print(result, type(result))
# ["name", "cali", "score", 100, "test0", false, "test1", null] <class 'str'>
result2 = json.loads(result)
print(result2, type(result2))
# ['name', 'cali', 'score', 100, 'test0', False, 'test1', None] <class 'list'>
OS模块
文件、文件夹操作
获取当前工作目录
import os
print(os.getcwd())
# E:\scpythonProject\2022_5_15
获取当前目录的文件和文件夹
print(os.listdir())
# ['os操作文件目录.py', 'test', 'time,datetime.py']
删除文件
os.remove("a.txt6")
os.remove("test/b.txt")
删除空目录
os.removedirs("test2")
os.removedirs("test")
# OSError: [WinError 145] 目录不是空的。: 'test'
不是空目录会报错
检测给出的路径是否为一个文件(如果路径不存在,不是文件 =》False)
print(os.path.isfile("E:\scpythonProject\2022_5_15"))
# False
print(os.path.isfile("./test/adfa.img"))
# True
print(os.path.isfile("./test"))
# False
检测给出的路径是否为一个目录
print(os.path.isdir("./test"))
# True
print(os.path.isdir("./test9"))
# False
常用,判断路径是否存在
print(os.path.exists("./test0"))
# False
print(os.path.exists("./test"))
# True
将路径的目录和文件进行切割
print(os.path.split("/home/swaroop/byte/code/poem.txt"))
# ('/home/swaroop/byte/code', 'poem.txt')
# 因为code后面有/,所以可以判断code为目录
print(os.path.split("/home/swaroop/byte/code/"))
# ('/home/swaroop/byte/code', '')
# 无法判断code是不是目录,默认为文件,因为linux中文件可以没有后缀
print(os.path.split("/home/swaroop/byte/code"))
# ('/home/swaroop/byte', 'code')
分割文件和扩展名
print(os.path.splitext('/home/swaroop/byte/code/poem.txt'))
# ('/home/swaroop/byte/code/poem', '.txt')
获取文件所在目录
print(os.path.dirname('/home/swaroop/byte/code/poem.txt'))
# /home/swaroop/byte/code
创建单文件 os.mkdir
os.mkdir("test3")
创建多级目录文件
os.makedirs("test4/dadf")
练习
查看指定路径下有哪些文件和文件夹
path = input("请输入你要查询的路径:")
print(os.listdir(path))
requests模块
requests的功能:提供网络请求服务
获取网页数据(文本浏览器),返回一个响应
response = requests.get(url="https://www.baidu.com")
print(response, type(response))
# <Response [200]> <class 'requests.models.Response'>
# 200 => http请求返回结果的状态码 =》 ok
输出网页的二进制内容
print(response.content)
输出状态码
print(response.status_code)
# 200
输出文本,自动转码
print(response.text)
# 自动将content转化为str格式 =》 html代码
# 不建议使用text自动识别 =》 失败了比较高
HTTP状态码
1xx消息——请求已被服务器接收,继续处理
2xx成功——请求已成功被服务器接收、理解、并接受
3xx重定向——需要后续操作才能完成这一请求
4xx请求错误——请求含有词法错误或者无法被执行
5xx服务器错误——服务器在处理某个正确请求时发生错误
常见状态代码、状态描述、说明:
200 OK //请求成功
400 Bad Request //客户端请求有语法错误,不能被服务器所理解
401 Unauthorized //请求未经授权,这个状态代码必须和WWW-Authenticate报头域一起使用
403 Forbidden //服务器收到请求,但是拒绝提供服务
404 Not Found //请求资源不存在,eg:输入了错误的URL
500 Internal Server Error //服务器发生不可预期的错误**503 Server Unavailable //服务器当前不能处理客户端的请求,一段时间后可能恢复正常
练习
- 获取这个png数据(https://n.sinaimg.cn/tech/680/w1920h360/20210322/21a9-kmrcukz9247632.png)
- 保存到文件 => 今天日期时间(202205151147.png)
- requests, open, time/datetime
result = requests.get(url="https://n.sinaimg.cn/tech/680/w1920h360/20210322/21a9-kmrcukz9247632.png")
date = datetime.datetime.today().strftime("%Y%m%d%H%M%S")
with open(f"{date}.png", 'wb') as fp:
fp.write(result.content)