【python零基础教程第7讲】常用标准库入门
·
Python 常用标准库入门:从随机数到日期处理,再到 JSON 与第三方库
Python 之所以被称为“内置电池”的语言,很大程度上归功于其丰富且强大的标准库。对于初学者来说,掌握几个最常用的标准库,就能解决日常开发中 80% 的常见需求。本文将从 random、time、datetime、json 四个核心模块入手,并补充几个高频使用的第三方库,带你快速上手。
一、random —— 随机数生成器
random 模块提供了生成伪随机数的各种函数,适用于模拟、游戏、抽样等场景。
1. 基础随机数
import random
# 生成 [0.0, 1.0) 之间的浮点数
print(random.random()) # 0.374540...
# 生成 [a, b] 之间的整数
print(random.randint(1, 10)) # 7
# 生成 [a, b) 之间的浮点数
print(random.uniform(1.5, 5.5)) # 3.14159...
2. 序列操作
items = ['苹果', '香蕉', '橘子', '西瓜']
# 随机选择一个元素
print(random.choice(items)) # 橘子
# 随机选择 k 个元素(不重复)
print(random.sample(items, 2)) # ['西瓜', '苹果']
# 打乱列表顺序(原地修改)
random.shuffle(items)
print(items) # ['香蕉', '西瓜', '苹果', '橘子']
3. 设置种子(可复现随机)
random.seed(42)
print(random.randint(1, 100)) # 82
random.seed(42) # 再次设置相同种子
print(random.randint(1, 100)) # 82(结果相同)
二、time —— 时间戳与休眠
time 模块主要处理时间戳(Unix 时间)和程序休眠。
1. 获取当前时间戳
import time
# 当前时间戳(秒,浮点数)
print(time.time()) # 1751760000.123456
# 将时间戳转换为可读字符串(本地时间)
print(time.ctime()) # Mon Jul 6 10:30:00 2026
2. 程序休眠
print("开始")
time.sleep(2) # 暂停 2 秒
print("2 秒后继续")
3. 结构化时间与格式化
# 获取结构化时间(本地时间)
local_time = time.localtime()
print(local_time.tm_year) # 2026
print(local_time.tm_mon) # 7
# 将结构化时间格式化为字符串
formatted = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
print(formatted) # 2026-07-06 10:30:00
# 将字符串解析为结构化时间
parsed = time.strptime("2026-07-06", "%Y-%m-%d")
print(parsed.tm_wday) # 0(星期一,0 表示周一)
三、datetime —— 更友好的日期时间处理
datetime 模块提供了面向对象的日期时间类,比 time 更直观、功能更强大。
1. 获取当前日期时间
from datetime import datetime, date, time, timedelta
now = datetime.now()
print(now) # 2026-07-06 10:30:00.123456
today = date.today()
print(today) # 2026-07-06
2. 创建指定日期时间
dt = datetime(2026, 7, 6, 10, 30, 0)
print(dt) # 2026-07-06 10:30:00
d = date(2026, 2, 17) # 2026 年春节
print(d) # 2026-02-17
3. 日期时间运算
# 加减时间间隔
one_week = timedelta(weeks=1)
next_week = now + one_week
print(next_week) # 2026-07-13 10:30:00.123456
# 计算两个日期之差
diff = next_week - now
print(diff.days) # 7
4. 格式化与解析
# 格式化输出
print(now.strftime("%A, %B %d, %Y")) # Monday, July 06, 2026
# 解析字符串
parsed = datetime.strptime("2026-07-06 10:30", "%Y-%m-%d %H:%M")
print(parsed) # 2026-07-06 10:30:00
5. 时区处理(Python 3.9+ 推荐使用 zoneinfo)
from zoneinfo import ZoneInfo
utc_now = datetime.now(ZoneInfo("UTC"))
beijing = utc_now.astimezone(ZoneInfo("Asia/Shanghai"))
print(beijing) # 2026-07-06 18:30:00+08:00
四、json —— 数据序列化与反序列化
json 模块用于在 Python 对象和 JSON 字符串之间转换,是 API 交互、配置文件读取的必备工具。
1. 序列化(Python → JSON)
import json
data = {
"name": "小艺",
"age": 3,
"skills": ["对话", "写作", "编程"],
"is_active": True,
"birthday": None
}
# 转换为 JSON 字符串
json_str = json.dumps(data, ensure_ascii=False, indent=2)
print(json_str)
# 输出:
# {
# "name": "小艺",
# "age": 3,
# "skills": ["对话", "写作", "编程"],
# "is_active": true,
# "birthday": null
# }
2. 反序列化(JSON → Python)
json_str = '{"name": "小艺", "age": 3}'
parsed = json.loads(json_str)
print(parsed["name"]) # 小艺
print(type(parsed)) # <class 'dict'>
3. 读写文件
# 写入 JSON 文件
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
# 读取 JSON 文件
with open("data.json", "r", encoding="utf-8") as f:
loaded = json.load(f)
4. 处理特殊类型(如 datetime)
from datetime import datetime
def datetime_serializer(obj):
if isinstance(obj, datetime):
return obj.isoformat()
raise TypeError(f"Type {type(obj)} not serializable")
now = datetime.now()
json_str = json.dumps({"time": now}, default=datetime_serializer)
print(json_str) # {"time": "2026-07-06T10:30:00.123456"}
五、常用第三方库推荐
标准库虽强,但有些场景需要更专业的工具。以下是几个高频使用的第三方库:
1. requests —— HTTP 请求
import requests
response = requests.get("https://api.github.com")
print(response.status_code) # 200
print(response.json()) # 自动解析 JSON
2. pandas —— 数据分析
import pandas as pd
df = pd.DataFrame({"姓名": ["张三", "李四"], "年龄": [25, 30]})
print(df.describe())
3. numpy —— 数值计算
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr.mean()) # 2.5
4. matplotlib —— 数据可视化
import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()
5. beautifulsoup4 + lxml —— 网页解析
from bs4 import BeautifulSoup
html = "<body><h1>标题"
soup = BeautifulSoup(html, "lxml")
print(soup.h1.text) # 标题
6. tqdm —— 进度条
from tqdm import tqdm
import time
for i in tqdm(range(100)):
time.sleep(0.01)
六、总结
| 模块/库 | 核心用途 | 入门要点 |
|---|---|---|
random |
生成随机数、随机选择 | randint、choice、shuffle、seed |
time |
时间戳、休眠、格式化 | time()、sleep()、strftime |
datetime |
日期时间运算、时区 | datetime、timedelta、strptime |
json |
数据序列化/反序列化 | dumps、loads、dump、load |
requests |
HTTP 请求 | get、post、json() |
pandas |
表格数据处理 | DataFrame、read_csv |
numpy |
数组与数学运算 | array、mean、reshape |
matplotlib |
绘图 | plot、show |
beautifulsoup4 |
HTML/XML 解析 | BeautifulSoup、find_all |
tqdm |
进度条显示 | tqdm 包裹可迭代对象 |
掌握这些工具,你已经可以应对绝大多数 Python 日常开发任务。
更多推荐



所有评论(0)