【python零基础教程第7讲】常用标准库入门 Python 常用标准库入门从随机数到日期处理再到 JSON 与第三方库Python 之所以被称为“内置电池”的语言很大程度上归功于其丰富且强大的标准库。对于初学者来说掌握几个最常用的标准库就能解决日常开发中 80% 的常见需求。本文将从random、time、datetime、json四个核心模块入手并补充几个高频使用的第三方库带你快速上手。一、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 20262. 程序休眠print(开始)time.sleep(2)# 暂停 2 秒print(2 秒后继续)3. 结构化时间与格式化# 获取结构化时间本地时间local_timetime.localtime()print(local_time.tm_year)# 2026print(local_time.tm_mon)# 7# 将结构化时间格式化为字符串formattedtime.strftime(%Y-%m-%d %H:%M:%S,local_time)print(formatted)# 2026-07-06 10:30:00# 将字符串解析为结构化时间parsedtime.strptime(2026-07-06,%Y-%m-%d)print(parsed.tm_wday)# 0星期一0 表示周一三、datetime —— 更友好的日期时间处理datetime模块提供了面向对象的日期时间类比time更直观、功能更强大。1. 获取当前日期时间fromdatetimeimportdatetime,date,time,timedelta nowdatetime.now()print(now)# 2026-07-06 10:30:00.123456todaydate.today()print(today)# 2026-07-062. 创建指定日期时间dtdatetime(2026,7,6,10,30,0)print(dt)# 2026-07-06 10:30:00ddate(2026,2,17)# 2026 年春节print(d)# 2026-02-173. 日期时间运算# 加减时间间隔one_weektimedelta(weeks1)next_weeknowone_weekprint(next_week)# 2026-07-13 10:30:00.123456# 计算两个日期之差diffnext_week-nowprint(diff.days)# 74. 格式化与解析# 格式化输出print(now.strftime(%A, %B %d, %Y))# Monday, July 06, 2026# 解析字符串parseddatetime.strptime(2026-07-06 10:30,%Y-%m-%d %H:%M)print(parsed)# 2026-07-06 10:30:005. 时区处理Python 3.9 推荐使用 zoneinfofromzoneinfoimportZoneInfo utc_nowdatetime.now(ZoneInfo(UTC))beijingutc_now.astimezone(ZoneInfo(Asia/Shanghai))print(beijing)# 2026-07-06 18:30:0008:00四、json —— 数据序列化与反序列化json模块用于在 Python 对象和 JSON 字符串之间转换是 API 交互、配置文件读取的必备工具。1. 序列化Python → JSONimportjson data{name:小艺,age:3,skills:[对话,写作,编程],is_active:True,birthday:None}# 转换为 JSON 字符串json_strjson.dumps(data,ensure_asciiFalse,indent2)print(json_str)# 输出# {# name: 小艺,# age: 3,# skills: [对话, 写作, 编程],# is_active: true,# birthday: null# }2. 反序列化JSON → Pythonjson_str{name: 小艺, age: 3}parsedjson.loads(json_str)print(parsed[name])# 小艺print(type(parsed))# class dict3. 读写文件# 写入 JSON 文件withopen(data.json,w,encodingutf-8)asf:json.dump(data,f,ensure_asciiFalse,indent2)# 读取 JSON 文件withopen(data.json,r,encodingutf-8)asf:loadedjson.load(f)4. 处理特殊类型如 datetimefromdatetimeimportdatetimedefdatetime_serializer(obj):ifisinstance(obj,datetime):returnobj.isoformat()raiseTypeError(fType{type(obj)}not serializable)nowdatetime.now()json_strjson.dumps({time:now},defaultdatetime_serializer)print(json_str)# {time: 2026-07-06T10:30:00.123456}五、常用第三方库推荐标准库虽强但有些场景需要更专业的工具。以下是几个高频使用的第三方库1.requests—— HTTP 请求importrequests responserequests.get(https://api.github.com)print(response.status_code)# 200print(response.json())# 自动解析 JSON2.pandas—— 数据分析importpandasaspd dfpd.DataFrame({姓名:[张三,李四],年龄:[25,30]})print(df.describe())3.numpy—— 数值计算importnumpyasnp arrnp.array([1,2,3,4])print(arr.mean())# 2.54.matplotlib—— 数据可视化importmatplotlib.pyplotasplt plt.plot([1,2,3],[4,5,6])plt.show()5.beautifulsoup4lxml—— 网页解析frombs4importBeautifulSoup htmlbodyh1标题soupBeautifulSoup(html,lxml)print(soup.h1.text)# 标题6.tqdm—— 进度条fromtqdmimporttqdmimporttimeforiintqdm(range(100)):time.sleep(0.01)六、总结模块/库核心用途入门要点random生成随机数、随机选择randint、choice、shuffle、seedtime时间戳、休眠、格式化time()、sleep()、strftimedatetime日期时间运算、时区datetime、timedelta、strptimejson数据序列化/反序列化dumps、loads、dump、loadrequestsHTTP 请求get、post、json()pandas表格数据处理DataFrame、read_csvnumpy数组与数学运算array、mean、reshapematplotlib绘图plot、showbeautifulsoup4HTML/XML 解析BeautifulSoup、find_alltqdm进度条显示tqdm包裹可迭代对象掌握这些工具你已经可以应对绝大多数 Python 日常开发任务。