掌握时间处理的基础:从导入到实战应用
Python 的 time 库是标准库之一,用于处理与时间相关的操作,如获取当前时间、格式化时间、暂停程序执行等。
它提供了一系列简单而强大的函数,适用于日志记录、性能测试、定时任务等场景。
导入方式非常简单,只需一行代码:
import time
这是最常见且推荐的方式。你也可以选择性地导入特定函数(不推荐初学者使用):
from time import sleep, time
但为了代码可读性和避免命名冲突,建议使用 import time。
time.time():返回自 Unix 纪元(1970年1月1日 00:00:00 UTC)以来的秒数(浮点数)。time.sleep(seconds):暂停程序执行指定的秒数。time.localtime([secs]):将时间戳转换为本地时间的 struct_time 对象。time.strftime(format[, t]):将时间格式化为字符串。import time
# 获取当前时间戳
now = time.time()
print("当前时间戳:", now)
# 暂停2秒
print("等待中...")
time.sleep(2)
print("继续执行!")
# 格式化当前时间
local_time = time.localtime(now)
formatted = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
print("格式化时间:", formatted)
time 和 datetime 模块。后者功能更强大,适合复杂日期操作。time.sleep() 是阻塞式的,不适合高并发场景(可考虑 asyncio 替代)。Q:导入 time 后为什么不能直接用 sleep()?
A:因为你是用 import time 导入的,必须通过 time.sleep() 调用。若想直接用 sleep(),需使用 from time import sleep。
Q:time 和 datetime 有什么区别?
A:time 更底层、轻量,适合简单计时;datetime 提供面向对象的时间处理,支持时区、日期运算等高级功能。