在日常编程中,时间处理几乎是每个项目都绕不开的需求------记录程序运行耗时、定时执行任务、生成时间戳日志、控制动画帧率、实现超时重试机制等。Python 的 time 模块提供了底层的时间访问函数,主要基于 Unix 时间戳(自 1970-01-01 00:00:00 UTC 以来的秒数)。它虽然不像 datetime 那样具备丰富的日期运算,但在性能监控 、延时控制 、高精度计时 、与系统时钟交互 等场景中无可替代。例如,在代码性能调优 时,你需要测量某段函数的执行时间;在爬虫程序 中,你需要礼貌地延时请求避免被封;在游戏开发 中,你需要控制帧速率使动画平滑;在日常脚本 里,你可能需要让程序等待几秒后再执行下一步。time 模块正是这些需求的基石。
一、安装库
time 是 Python 标准库,无需安装。直接导入即可:
python
import time
常用函数:time()、sleep()、perf_counter()、process_time()、strftime()、gmtime()、localtime()。
二、基本用法
下面通过 4 个小步骤,掌握 time 的核心功能。
1. 获取时间戳(秒数)
python
import time
timestamp = time.time() # 返回浮点数,如 1698765432.123456
print(f"当前时间戳: {timestamp}")
时间戳便于做差值计算和国际化存储。
2. 让程序暂停(睡眠)
python
print("开始")
time.sleep(2) # 暂停 2 秒
print("2 秒后执行")
sleep 接受浮点数,可实现毫秒级延时:time.sleep(0.5)。
3. 时间戳转结构化时间
python
# 本地时间(带时区)
local = time.localtime() # 或 time.localtime(timestamp)
print(local.tm_year, local.tm_mon, local.tm_mday)
# UTC 时间
utc = time.gmtime()
print(utc.tm_hour) # 小时(0-23)
4. 格式化时间字符串
python
# 结构化时间 → 字符串
formatted = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(formatted) # 2025-05-18 14:30:00
# 字符串 → 结构化时间(需要格式匹配)
struct = time.strptime("2025-05-18 14:30:00", "%Y-%m-%d %H:%M:%S")
常用格式码:%Y(四位年)、%m(月)、%d(日)、%H(24小时)、%M(分)、%S(秒)。
三、高级用法
高精度计时器:perf_counter()
time.time() 精度受系统时钟影响(可能受 NTP 调整),且不适合测量短时间间隔。perf_counter() 提供最高可用精度的时钟,专门用于性能测量,单调递增不受系统时间修改影响。
python
start = time.perf_counter()
# 执行一段代码
for _ in range(10**6):
pass
end = time.perf_counter()
print(f"耗时: {(end - start)*1000:.3f} 毫秒")
进程 CPU 时间:process_time()
process_time() 返回当前进程消耗的 CPU 时间(不包括 sleep 时间),用于测量纯 CPU 运算耗时。
python
cpu_start = time.process_time()
# CPU 密集型任务
sum(i**2 for i in range(10**6))
cpu_end = time.process_time()
print(f"CPU 时间: {cpu_end - cpu_start:.3f} 秒")
监控程序执行时间装饰器
python
import time
from functools import wraps
def timer(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed = time.perf_counter() - start
print(f"{func.__name__} 耗时: {elapsed:.6f} 秒")
return result
return wrapper
@timer
def heavy_computation():
time.sleep(0.5) # 模拟 I/O
return 42
超时控制(使用 signal 或 threading,简单示例)
虽然 time 本身不支持超时,但可配合 threading.Timer 实现:
python
import time
import threading
def timeout_handler():
print("操作超时!")
timer = threading.Timer(3.0, timeout_handler)
timer.start()
# 模拟一个可能耗时的操作
time.sleep(5) # 假设操作耗时 5 秒
timer.cancel() # 如果操作提前完成,取消定时器
实际生产可考虑 func_timeout 库,但原理类似。
四、实际应用场景
场景1:接口请求限流与重试(带指数退避)
python
import time
import random
def fetch_with_retry(url, max_retries=3, base_delay=1):
for attempt in range(max_retries):
try:
# 模拟请求
print(f"尝试第 {attempt+1} 次请求 {url}")
if random.random() < 0.7: # 70% 模拟失败
raise Exception("网络错误")
return "成功响应"
except Exception as e:
if attempt == max_retries - 1:
raise
delay = base_delay * (2 ** attempt) # 1, 2, 4 秒
print(f"失败,{delay:.1f} 秒后重试...")
time.sleep(delay)
# 使用
result = fetch_with_retry("https://api.example.com/data")
print(result)
此场景在真实爬虫或微服务调用中非常常见,time.sleep() 实现了优雅的重试间隔。
场景2:制作一个简单的"番茄工作法"计时器
python
import time
import sys
def tomato_timer(minutes):
seconds = minutes * 60
print(f"番茄钟开始:{minutes} 分钟")
for remaining in range(seconds, 0, -1):
sys.stdout.write(f"\r剩余时间: {remaining//60:02d}:{remaining%60:02d}")
sys.stdout.flush()
time.sleep(1)
print("\n时间到!休息一下吧~")
tomato_timer(25) # 25 分钟专注
这个例子结合了 sleep 和动态刷新终端,可用于开发自己的效率工具。
场景3:代码性能对比(高精度计时)
python
import time
def method_a(n):
return [i**2 for i in range(n)]
def method_b(n):
result = []
for i in range(n):
result.append(i**2)
return result
n = 10**6
start = time.perf_counter()
method_a(n)
mid = time.perf_counter()
method_b(n)
end = time.perf_counter()
print(f"列表推导式: {(mid - start)*1000:.2f} ms")
print(f"循环append: {(end - mid)*1000:.2f} ms")
实际优化时常需要用 perf_counter() 对比不同写法的性能。
五、结尾互动
time 模块虽小,却是 Python 时间处理的基础设施。它提供的时间戳、休眠、高精度计时、格式化转换等功能,覆盖了从性能测试到流程控制的方方面面。需要记住的是:time 更擅长处理"时刻"和"间隔"这种底层概念,而复杂的日期运算(如加一个月、计算年龄)请交给 datetime;跨时区转换请用 pytz 或 zoneinfo。不过,当你要精准测量一段代码跑了多久、让程序优雅地等待、或者记录事件发生的绝对时间戳时,time 永远是最直接可靠的选择。
你在日常开发中是否用 time 做过有趣的事情?比如写一个倒计时小脚本、监控服务器响应时间,或者实现简单的限流器?欢迎在评论区分享你的实践或遇到的坑,咱们一起探讨时间编程的艺术。