Python时间处理与系统模块实战指南
1. Python时间处理模块深度解析1.1 time模块实战应用time模块是Python处理时间的底层基础模块提供了各种时间相关的函数。在实际开发中最常用的几个功能点包括时间戳获取与转换time.time()返回当前时间戳1970纪元后经过的浮点秒数这个功能在性能测试、日志记录等场景非常实用。比如计算代码执行时间import time start time.time() # 执行一些操作 time.sleep(2.5) # 模拟耗时操作 end time.time() print(f操作耗时: {end - start:.2f}秒)时间格式化strftime和strptime是时间字符串与时间元组相互转换的关键方法。开发中常见的日期格式转换问题大多可以通过这两个函数解决。格式字符串中%Y表示4位年份%m表示2位月份%d表示2位日期%H表示24小时制小时%M表示分钟%S表示秒注意Windows和Linux系统对某些格式符号的支持可能不同比如%z时区支持在Windows上可能有问题。1.2 datetime模块高级用法datetime模块在time模块基础上提供了更高级的日期时间处理功能主要包含datetime.date处理日期年、月、日datetime.time处理时间时、分、秒、微秒datetime.datetime处理日期和时间datetime.timedelta处理时间间隔一个典型应用场景是计算到期日from datetime import datetime, timedelta current_date datetime.now() due_date current_date timedelta(days30) print(f当前时间: {current_date.strftime(%Y-%m-%d)}) print(f30天后到期: {due_date.strftime(%Y-%m-%d)})时区处理是datetime的难点建议使用pytz库进行跨时区转换from datetime import datetime import pytz utc pytz.utc local_tz pytz.timezone(Asia/Shanghai) utc_time datetime.now(utc) local_time utc_time.astimezone(local_tz) print(fUTC时间: {utc_time}) print(f本地时间: {local_time})2. 随机数与系统操作模块详解2.1 random模块的实战技巧random模块不仅用于生成随机数在实际项目中有多种应用场景验证码生成结合数字和字母import random import string def generate_code(length6): chars string.ascii_letters string.digits return .join(random.choice(chars) for _ in range(length)) print(f验证码: {generate_code()})权重随机选择如抽奖系统items [一等奖, 二等奖, 三等奖, 谢谢参与] weights [0.01, 0.09, 0.3, 0.6] # 对应概率 result random.choices(items, weightsweights, k1)[0] print(f抽奖结果: {result})列表随机排序如音乐播放列表playlist [song1, song2, song3, song4, song5] random.shuffle(playlist) print(f随机播放顺序: {playlist})重要提示random模块生成的随机数实际上是伪随机数不适合安全敏感场景如密码生成这种情况下应使用secrets模块。2.2 os模块的深度应用os模块是与操作系统交互的重要接口以下是一些高级用法跨平台路径处理import os # 安全拼接路径 config_path os.path.join(os.path.expanduser(~), app, config.ini) print(f配置文件路径: {config_path}) # 获取文件信息 file_stats os.stat(config_path) print(f文件大小: {file_stats.st_size}字节)递归遍历目录替代os.walk的生成器实现def scan_dir(path): for entry in os.scandir(path): if entry.is_dir(): yield from scan_dir(entry.path) else: yield entry.path for file_path in scan_dir(/path/to/directory): print(file_path)环境变量管理# 安全获取环境变量 db_host os.getenv(DB_HOST, localhost) # 提供默认值 print(f数据库地址: {db_host}) # 临时修改环境变量不影响系统环境 os.environ[TEMP_VAR] test_value3. 文件与数据处理模块实战3.1 shutil模块的高级文件操作shutil模块提供了比os模块更高级的文件操作功能安全文件复制保留元数据import shutil def safe_copy(src, dst): try: shutil.copy2(src, dst) # 保留所有元数据 print(f文件复制成功: {src} - {dst}) except IOError as e: print(f复制失败: {e}) safe_copy(source.txt, backup/source.txt)目录树操作带进度显示from shutil import copytree, rmtree import sys def copy_with_progress(src, dst): def _progress(cur, total): sys.stdout.write(f\r进度: {cur/total:.1%}) sys.stdout.flush() print(f正在复制 {src} 到 {dst}) copytree(src, dst, copy_functionshutil.copy2, ignoreshutil.ignore_patterns(*.tmp), dirs_exist_okTrue) print(\n复制完成) copy_with_progress(source_dir, backup_dir)磁盘空间检查跨平台方案def check_disk_space(path, min_space_gb1): stat shutil.disk_usage(path) free_gb stat.free / (1024**3) if free_gb min_space_gb: raise RuntimeError(f磁盘空间不足: 需要{min_space_gb}GB, 可用{free_gb:.2f}GB) print(f可用空间: {free_gb:.2f}GB) check_disk_space(/, min_space_gb5)3.2 json与pickle序列化对比Python中常用的序列化模块对比特性json模块pickle模块安全性安全不安全可执行任意代码跨语言支持仅Python数据类型基本类型几乎所有Python对象性能较慢较快文件大小较大较小json使用示例带美化输出import json data { name: 张三, age: 30, skills: [Python, SQL, Linux] } # 序列化到文件 with open(data.json, w, encodingutf-8) as f: json.dump(data, f, ensure_asciiFalse, indent2) # 从文件反序列化 with open(data.json, r, encodingutf-8) as f: loaded json.load(f) print(loaded)pickle高级用法自定义对象序列化import pickle class User: def __init__(self, name, age): self.name name self.age age def __repr__(self): return fUser(name{self.name}, age{self.age}) user User(李四, 25) # 序列化 with open(user.pkl, wb) as f: pickle.dump(user, f, protocolpickle.HIGHEST_PROTOCOL) # 反序列化 with open(user.pkl, rb) as f: loaded_user pickle.load(f) print(loaded_user)安全警告永远不要反序列化不受信任来源的pickle数据这可能导致代码执行漏洞。4. 配置处理与正则表达式实战4.1 configparser的高级配置管理configparser模块用于处理INI格式的配置文件支持多级配置和类型转换安全配置读取带默认值和类型转换from configparser import ConfigParser from pathlib import Path config ConfigParser() config.read_dict({ DEFAULT: { timeout: 30, retry: 3 }, database: { host: localhost, port: 5432 } }) # 类型安全读取 def get_config(section, option, type_funcstr, defaultNone): try: value config.get(section, option) return type_func(value) except (ValueError, KeyError): return default timeout get_config(DEFAULT, timeout, int, 10) db_host get_config(database, host, default127.0.0.1)配置自动保存修改后立即持久化class AutoSaveConfigParser(ConfigParser): def __init__(self, filename, **kwargs): super().__init__(**kwargs) self.filename filename self.read(filename) def set(self, section, option, valueNone): super().set(section, option, value) with open(self.filename, w) as f: self.write(f) config AutoSaveConfigParser(settings.ini) config.set(database, host, new_host)4.2 正则表达式高级技巧re模块是Python中处理正则表达式的标准模块以下是一些高级用法预编译正则表达式提升性能import re # 预编译常用正则 EMAIL_REGEX re.compile(r^[a-zA-Z0-9._%-][a-zA-Z0-9.-]\.[a-zA-Z]{2,}$) PHONE_REGEX re.compile(r^1[3-9]\d{9}$) def validate_email(email): return bool(EMAIL_REGEX.fullmatch(email)) print(validate_email(testexample.com)) # True print(validate_email(invalid.email)) # False命名捕获组提高可读性log_pattern re.compile( r(?Pip\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) - - r\[(?Ptimestamp.*?)\] r(?Pmethod\w) (?Purl.*?) HTTP/\d\.\d r(?Pstatus\d{3}) r(?Psize\d) ) log_line 127.0.0.1 - - [10/Oct/2023:13:55:36 0800] GET /api/user HTTP/1.1 200 432 match log_pattern.match(log_line) if match: print(fIP: {match.group(ip)}) print(f方法: {match.group(method)}) print(f状态码: {match.group(status)})复杂文本替换使用回调函数text 订单号: 12345, 金额: 100.50; 订单号: 67890, 金额: 200.75 def mask_order(match): order_id match.group(order_id) amount float(match.group(amount)) return f订单号: {order_id[:2]}***, 金额: {amount * 1.1:.2f}含税 pattern re.compile( r订单号: (?Porder_id\d), 金额: (?Pamount\d\.\d{2}) ) result pattern.sub(mask_order, text) print(result)性能优化技巧对于简单匹配str方法如startswith()、endswith()比正则更快使用非贪婪匹配.*?避免回溯问题复杂正则可以拆分为多个简单正则分步处理考虑使用re.VERBOSE标志提高复杂正则的可读性