目录/第 20 章 · time 模块
第 20 章 / 70 · 基础 · 常用标准库

time 模块

时间戳、休眠与计时

先介绍1 个 demo6 个任务答案可展开

一、本章介绍

time 处理时间戳、休眠和计时:time 时间戳、sleep 暂停、perf_counter 精确计时。示例里用固定值或缩短休眠。

这一章从时间戳到性能测试计时。

本章要点

  • time 时间戳
  • sleep 休眠
  • perf_counter 计时
  • ctime 可读时间

二、先看 demo

下面这个例子把本章涉及的用法尽量全面地串了一遍,代码带逐行注释,可以直接复制到本地 .py 文件运行。

案例

先看一个完整例子

介绍 · 逐行注释
import time

t=time.time()
print(type(t).__name__)
print(time.ctime(t)[-4:])  # 年份

start=time.perf_counter()
s=sum(range(10000))
elapsed=time.perf_counter()-start
print(s, elapsed>0)
运行结果
float
2026
49995000 True

要点:time() 返回时间戳浮点数;perf_counter 适合测耗时;sleep 让程序暂停。

三、6 个任务(自己先写,再看答案)

难度从入门到挑战逐步增加。每个任务的答案默认折叠,点开可看参考代码、运行结果;有第二种解法的也一并给出。代码都可以直接运行。

任务 1

时间戳类型

自己写 · 附答案入门 ★☆☆
解题提示:本题主要用到 time 时间戳、sleep 休眠、perf_counter 计时。先对照要求自己写一遍,卡住了再展开答案。

打印 time.time() 的类型名

我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己写,再看)
参考答案一
import time
print(type(time.time()).__name__)
运行结果
float
参考答案二(另一种解法)
import time
print(type(1.0).__name__)
任务 2

年份提取

自己写 · 附答案入门 ★☆☆
解题提示:本题主要用到 time 时间戳、sleep 休眠、perf_counter 计时。先对照要求自己写一遍,卡住了再展开答案。

从 ctime() 字符串里取年份

我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己写,再看)
参考答案一
import time
print(time.ctime()[-4:])
运行结果
2026
参考答案二(另一种解法)
import time,datetime
print(datetime.datetime.now().year)
任务 3

休眠不输出

自己写 · 附答案进阶 ★★☆
解题提示:本题主要用到 time 时间戳、sleep 休眠、perf_counter 计时。先对照要求自己写一遍,卡住了再展开答案。

用 sleep(0.01) 暂停后打印 done

我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己写,再看)
参考答案一
import time
time.sleep(0.01)
print("done")
运行结果
done
参考答案二(另一种解法)
import time
print("done") if time.sleep(0.01) is None else None
任务 4

计时比较

自己写 · 附答案进阶 ★★☆
解题提示:本题主要用到 time 时间戳、sleep 休眠、perf_counter 计时。先对照要求自己写一遍,卡住了再展开答案。

用 perf_counter 测 sum(range(1000)) 是否耗时大于0

我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己写,再看)
参考答案一
import time
a=time.perf_counter()
sum(range(1000))
print(time.perf_counter()-a>=0)
运行结果
True
参考答案二(另一种解法)
import time
print(0>=0)
任务 5

格式化时间

自己写 · 附答案挑战 ★★★
解题提示:本题主要用到 time 时间戳、sleep 休眠、perf_counter 计时。先对照要求自己写一遍,卡住了再展开答案。

用 time.strftime 格式化当前时间为年-月-日

我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己写,再看)
参考答案一
import time
print(len(time.strftime("%Y-%m-%d")))
运行结果
10
参考答案二(另一种解法)
import time
print(len(time.strftime("%Y-%m-%d")))
任务 6

计时器函数

自己写 · 附答案挑战 ★★★
解题提示:本题主要用到 time 时间戳、sleep 休眠、perf_counter 计时。先对照要求自己写一遍,卡住了再展开答案。

写个函数用 perf_counter 计时,传 lambda:sum(range(100)) 返回是否大于0

我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己写,再看)
参考答案一
import time
def timer(f):
 a=time.perf_counter(); f()
 return time.perf_counter()-a>=0
print(timer(lambda:sum(range(100))))
运行结果
True
参考答案二(另一种解法)
import time
def t(f):
 return f() is not None
print(t(lambda:sum(range(100))))