【python零基础教程第7讲】常用标准库入门

Python 常用标准库入门:从随机数到日期处理,再到 JSON 与第三方库

Python 之所以被称为“内置电池”的语言,很大程度上归功于其丰富且强大的标准库。对于初学者来说,掌握几个最常用的标准库,就能解决日常开发中 80% 的常见需求。本文将从randomtimedatetimejson四个核心模块入手,并补充几个高频使用的第三方库,带你快速上手。


一、random —— 随机数生成器

random模块提供了生成伪随机数的各种函数,适用于模拟、游戏、抽样等场景。

1. 基础随机数

importrandom# 生成 [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))# 82random.seed(42)# 再次设置相同种子print(random.randint(1,100))# 82(结果相同)

二、time —— 时间戳与休眠

time模块主要处理时间戳(Unix 时间)和程序休眠。

1. 获取当前时间戳

importtime# 当前时间戳(秒,浮点数)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)# 2026print(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. 获取当前日期时间

fromdatetimeimportdatetime,date,time,timedelta now=datetime.now()print(now)# 2026-07-06 10:30:00.123456today=date.today()print(today)# 2026-07-06

2. 创建指定日期时间

dt=datetime(2026,7,6,10,30,0)print(dt)# 2026-07-06 10:30:00d=date(2026,2,17)# 2026 年春节print(d)# 2026-02-17

3. 日期时间运算

# 加减时间间隔one_week=timedelta(weeks=1)next_week=now+one_weekprint(next_week)# 2026-07-13 10:30:00.123456# 计算两个日期之差diff=next_week-nowprint(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)

fromzoneinfoimportZoneInfo 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)

importjson 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 文件withopen("data.json","w",encoding="utf-8")asf:json.dump(data,f,ensure_ascii=False,indent=2)# 读取 JSON 文件withopen("data.json","r",encoding="utf-8")asf:loaded=json.load(f)

4. 处理特殊类型(如 datetime)

fromdatetimeimportdatetimedefdatetime_serializer(obj):ifisinstance(obj,datetime):returnobj.isoformat()raiseTypeError(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 请求

importrequests response=requests.get("https://api.github.com")print(response.status_code)# 200print(response.json())# 自动解析 JSON

2.pandas—— 数据分析

importpandasaspd df=pd.DataFrame({"姓名":["张三","李四"],"年龄":[25,30]})print(df.describe())

3.numpy—— 数值计算

importnumpyasnp arr=np.array([1,2,3,4])print(arr.mean())# 2.5

4.matplotlib—— 数据可视化

importmatplotlib.pyplotasplt plt.plot([1,2,3],[4,5,6])plt.show()

5.beautifulsoup4+lxml—— 网页解析

frombs4importBeautifulSoup html="<body><h1>标题"soup=BeautifulSoup(html,"lxml")print(soup.h1.text)# 标题

6.tqdm—— 进度条

fromtqdmimporttqdmimporttimeforiintqdm(range(100)):time.sleep(0.01)

六、总结

模块/库核心用途入门要点
random生成随机数、随机选择randintchoiceshuffleseed
time时间戳、休眠、格式化time()sleep()strftime
datetime日期时间运算、时区datetimetimedeltastrptime
json数据序列化/反序列化dumpsloadsdumpload
requestsHTTP 请求getpostjson()
pandas表格数据处理DataFrameread_csv
numpy数组与数学运算arraymeanreshape
matplotlib绘图plotshow
beautifulsoup4HTML/XML 解析BeautifulSoupfind_all
tqdm进度条显示tqdm包裹可迭代对象

掌握这些工具,你已经可以应对绝大多数 Python 日常开发任务。