大多数 Python 开发者都熟悉 time 模块,由于它提供了诸如 time.sleep() 等实用函数。这使得该模块成为暂停执行的常用工具,这是一个简单但必不可少的工具。不过,time 模块的功能远不止于此,它提供了一套用于准确测量、时间转换和格式化的功能,这些功能往往被忽视。探索这些功能可以解锁更高效处理数据科学和其他编程项目中时间相关任务的方法。
# 1. 使用time.monotonic()准确测量经过的实际时间
虽然你可能习惯用 time.time() 来测量函数执行的时间,但它有一个关键缺陷:它基于系统时钟 ,而系统时钟可能被手动更改或受网络时间协议影响。这会导致时间差异不准确甚至出现负值。更可靠的解决方案是 time.monotonic()。这个函数返回单调时钟的值,该时钟不会倒退且不受系统时间更新影响。这的确 使其成为可靠测量持续时间的理想选择。
import time
start_time = time.monotonic()
# Simulate a task
time.sleep(2)
end_time = time.monotonic()
duration = end_time - start_time
print(f"The task took {duration:.2f} seconds.")
输出:
The task took 2.01 seconds.
# 2. 使用time.process_time()测量 CPU 处理时间
有时,你并不关心总经过的时间(墙上时间)。相反,你可能想知道 CPU 实际花费了多少时间来执行你的代码。这对于基准测试算法效率至关重大,由于它忽略了睡眠或等待 I/O 操作所花费的时间。time.process_time() 函数返回当前进程的系统和用户 CPU 时间的总和,提供了一个纯粹的衡量计算工作量的指标。
import time
start_cpu = time.process_time()
# A CPU-intensive task
total = 0
for i in range(10_000_000):
total += i
end_cpu = time.process_time()
cpu_duration = end_cpu - start_cpu
print(f"The CPU-intensive task took {cpu_duration:.2f} CPU seconds.")
输出:
The CPU-intensive task took 0.44 CPU seconds.
# 3. 使用time.perf_counter()获取高精度时间戳
对于需要高精度计时的场景,尤其是超级短的持续时间,time.perf_counter() 是一个必不可少的工具。它返回一个高分辨率性能计数器的值,这是系统上可用的最准确的时钟。这是一个系统范围内的计数,包括睡眠期间经过的时间,这使得它在每个纳秒都至关重大的基准测试场景中超级完美。
import time
start_perf = time.perf_counter()
# A very short operation
_ = [x*x for x in range(1000)]
end_perf = time.perf_counter()
perf_duration = end_perf - start_perf
print(f"The short operation took {perf_duration:.6f} seconds.")
输出:
The short operation took 0.000028 seconds.
# 4. 使用time.ctime()将时间戳转换为可读字符串
time.time() 的输出是一个浮点数,表明自”纪元”(对于 Unix 系统是 1970 年 1 月 1 日)以来的秒数。虽然它对计算很有用,但不是人类可读的。time.ctime() 函数接收这个时间戳,并将其转换为标准、易于阅读的字符串格式,例如'Thu Jul 31 16:32:30 2025'。
import time
current_timestamp = time.time()
readable_time = time.ctime(current_timestamp)
print(f"Timestamp: {current_timestamp}")
print(f"Readable Time: {readable_time}")
输出:
Timestamp: 1754044568.821037
Readable Time: Fri Aug 1 06:36:08 2025
# 5. 使用time.strptime()从字符串中解析时间
假设你有一个存储为字符串的时间信息,需要将其转换为结构化时间对象以进行进一步处理。time.strptime()(字符串解析时间)就是你的函数。你提供字符串和一个格式代码,该代码指定日期和时间组件的排列方式。它返回一个 struct_time 对象,这是一个包含元素(如年、月、日等)的元组,然后可以从中提取这些元素。
import time
date_string = "31 July, 2025"
format_code = "%d %B, %Y"
time_struct = time.strptime(date_string, format_code)
print(f"Parsed time structure: {time_struct}")
print(f"Year: {time_struct.tm_year}, Month: {time_struct.tm_mon}")
输出:
Parsed time structure: time.struct_time(tm_year=2025, tm_mon=7, tm_mday=31, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=212, tm_isdst=-1)
Year: 2025, Month: 7
# 6. 使用time.strftime()将时间格式化为自定义字符串
解析的相反操作是格式化。time.strftime()(字符串格式化时间)接受一个 struct_time 对象(例如由 strptime 或 localtime 返回的对象),并根据您指定的格式代码将其格式化为字符串。这为您提供了完全的控制权,无论您更喜爱”2025-07-31″还是”Thursday, July 31″。
import time
# Get current time as a struct_time object
current_time_struct = time.localtime()
# Format it in a custom way
formatted_string = time.strftime("%Y-%m-%d %H:%M:%S", current_time_struct)
print(f"Custom formatted time: {formatted_string}")
day_of_week = time.strftime("%A", current_time_struct)
print(f"Today is {day_of_week}.")
输出:
Custom formatted time: 2025-08-01 06:41:33
Today is Friday
# 7. 使用time.timezone和time.tzname获取基本时区信息
虽然 datetime 模块(以及像 pytz 这样的库)更适合处理复杂的时区,但 time 模块提供了一些基本信息。time.timezone 提供了本地非夏令时(Daylight Savings Time)时区相对于 UTC 西侧的偏移秒数,而 time.tzname 是一个包含本地非夏令时和夏令时时区名称的元组。
import time
# Offset in seconds west of UTC
offset_seconds = time.timezone
# Timezone names (standard, daylight saving)
tz_names = time.tzname
print(f"Timezone offset: {offset_seconds / 3600} hours west of UTC")
print(f"Timezone names: {tz_names}")
输出:
Timezone offset: 5.0 hours west of UTC
Timezone names: ('EST', 'EDT')
# 8. 使用time.gmtime()和time.localtime()在 UTC 时间和本地时间之间进行转换
处理不同的时区可能会很棘手。一个常见的做法是所有时间数据都存储为协调世界时(UTC),仅在显示时才转换为本地时间。`time` 模块通过 `time.gmtime()` 和 `time.localtime()` 函数来简化这一过程。这些函数接受一个以秒为单位的时间戳,并返回一个 `struct_time` 对象——`gmtime()` 以 UTC 返回它,而 `localtime()` 则返回系统配置的时区的时间。
import time
timestamp = time.time()
# Convert timestamp to struct_time in UTC
utc_time = time.gmtime(timestamp)
# Convert timestamp to struct_time in local time
local_time = time.localtime(timestamp)
print(f"UTC Time: {time.strftime('%Y-%m-%d %H:%M:%S', utc_time)}")
print(f"Local Time: {time.strftime('%Y-%m-%d %H:%M:%S', local_time)}")
输出:
UTC Time: 2025-08-01 10:47:58
Local Time: 2025-08-01 06:47:58
# 9. 使用time.mktime()实现time.time()的逆操作
time.localtime() 将时间戳转换为 struct_time 对象,这很有用… 但如何反向操作?time.mktime() 函数正好可以实现这一点。它接受一个 struct_time 对象(表明本地时间),并将其转换回一个浮点数,代表自纪元以来的秒数。这有助于计算未来或过去的时间戳或执行日期运算。
import time
# Get current local time structure
now_struct = time.localtime()
# Create a modified time structure for one hour from now
future_struct_list = list(now_struct)
future_struct_list[3] += 1 # Add 1 to the hour (tm_hour)
future_struct = time.struct_time(future_struct_list)
# Convert back to a timestamp
future_timestamp = time.mktime(future_struct)
print(f"Current timestamp: {time.time():.0f}")
print(f"Timestamp in one hour: {future_timestamp:.0f}")
输出:
Current timestamp: 1754045415
Timestamp in one hour: 1754049015
# 10. 使用time.thread_time()获取线程特定的 CPU 时间
在多线程应用程序中,time.process_time() 会给你整个进程的总 CPU 时间。但如果你想要分析特定线程的 CPU 使用情况呢?这时,time.thread_time() 就是你要找的函数。这个函数返回当前线程的系统和用户 CPU 时间的总和,使你能够识别哪些线程是计算成本最高的。
import time
import threading
def worker_task():
start_thread_time = time.thread_time()
# Simulate work
_ = [i * i for i in range(10_000_000)]
end_thread_time = time.thread_time()
print(f"Worker thread CPU time: {end_thread_time - start_thread_time:.2f}s")
# Run the task in a separate thread
thread = threading.Thread(target=worker_task)
thread.start()
thread.join()
print(f"Total process CPU time: {time.process_time():.2f}s")
输出:
Worker thread CPU time: 0.23s
Total process CPU time: 0.32s
# 总结
time 模块是 Python 标准库中一个重大且强劲的组成部分。虽然 time.sleep() 无疑是它最著名的函数,但其在计时、时长测量和时间格式化方面的能力,使它成为各种实用任务的得力工具。






