【重要】time库函数简介及简单用法示例
由于您提到的部分项(如 _STRUCT_TM_ITEMS, __doc__, __loader__, __name__, __package__, __spec__)并不是 time 库中用于时间处理的函数,而是模块的内部属性或特殊变量,因此我将只列出与时间处理相关的函数,并按照您的要求以表格形式展示。
| 序号 | 函数名 | 简介 | 简单用法示例 |
|---|---|---|---|
| 1 | altzone |
返回与 UTC 相差的夏令时秒数(如果适用) | print(time.altzone) |
| 2 | asctime |
将 struct_time 转换为可读字符串 |
print(time.asctime()) |
| 3 | clock |
返回处理器时间(已弃用,使用 process_time 或 perf_counter 替代) |
print(time.clock())(不推荐) |
| 4 | ctime |
将时间戳转换为可读字符串 | print(time.ctime(time.time())) |
| 5 | daylight |
如果系统使用夏令时,则返回非零值 | print(time.daylight) |
| 6 | get_clock_info |
返回有关给定时钟的信息 | print(time.get_clock_info('perf_counter')) |
| 7 | gmtime |
将时间戳转换为 UTC 时间的 struct_time |
print(time.gmtime()) |
| 8 | localtime |
将时间戳转换为本地时间的 struct_time |
print(time.localtime()) |
| 9 | mktime |
将 struct_time 转换为时间戳 |
t = time.localtime(); print(time.mktime(t)) |
| 10 | monotonic |
返回单调时钟的时间(不受系统时间更改影响) | print(time.monotonic()) |
| 11 | monotonic_ns |
返回单调时钟的时间(纳秒) | print(time.monotonic_ns()) |
| 12 | perf_counter |
返回高分辨率的性能计数器(用于测量短时间间隔) | print(time.perf_counter()) |
| 13 | perf_counter_ns |
返回高分辨率的性能计数器(纳秒) | print(time.perf_counter_ns()) |
| 14 | process_time |
返回当前进程的系统和用户 CPU 时间 | print(time.process_time()) |
| 15 | process_time_ns |
返回当前进程的系统和用户 CPU 时间(纳秒) | print(time.process_time_ns()) |
| 16 | sleep |
暂停当前线程指定的秒数 | time.sleep(2)(暂停 2 秒) |
| 17 | strftime |
根据格式字符串将 struct_time 转换为字符串 |
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) |
| 18 | strptime |
根据格式字符串解析时间字符串为 struct_time |
t = time.strptime("2023-01-01 12:00:00", "%Y-%m-%d %H:%M:%S"); print(t) |
| 19 | struct_time |
用于表示时间的命名元组 | t = time.localtime(); print(t.tm_year, t.tm_mon, t.tm_mday) |
| 20 | thread_time |
返回当前线程的 CPU 时间 | print(time.thread_time()) |
| 21 | thread_time_ns |
返回当前线程的 CPU 时间(纳秒) | print(time.thread_time_ns()) |
| 22 | time |
返回当前时间的时间戳 | print(time.time()) |
| 23 | time_ns |
返回当前时间的时间戳(纳秒) | print(time.time_ns()) |
| 24 | timezone |
返回与 UTC 相差的秒数(不考虑夏令时) | print(time.timezone) |
| 25 | tzname |
返回一个包含本地时区名称的元组(标准时间和夏令时) | print(time.tzname) |
请注意,部分函数(如 clock)在 Python 的较新版本中已被弃用,建议使用替代函数。

浙公网安备 33010602011771号