time 是 Python 中的一个内置模块,它提供了各种与时间相关的功能。
| 函数 | 描述 | 代码示例 |
|---|---|---|
time.time() | 获取当前时间的时间戳(自1970年1月1日以来的秒数) | start = time.time() |
time.ctime() | 将时间戳转换为可读的本地时间字符串 | print("当前时间:", time.ctime()) |
time.localtime() | 将时间戳转换为本地时间的 struct_time 对象 | local_time = time.localtime() |
time.gmtime() | 将时间戳转换为格林尼治标准时间的 struct_time 对象 | gmt_time = time.gmtime() |
time.sleep(seconds) | 暂停执行指定的秒数 | time.sleep(5) # 暂停5秒 |
time.strftime(format[, tuple]) | 将 struct_time 对象或时间戳格式化为字符串 | formatted_time = time.strftime('%Y-%m-%d %H:%M:%S', local_time) |
time.strptime(string[, format]) | 将字符串解析为 struct_time 对象 | struct_time = time.strptime('2024-05-31 12:00:00', '%Y-%m-%d %H:%M:%S') |
time.mktime(tuple) | 将 struct_time 对象转换为时间戳 | timestamp = time.mktime(local_time) |
time.perf_counter() | 返回一个性能计数器的值,用于测量短时间段 | start = time.perf_counter(); # 执行代码 end = time.perf_counter(); print(f"耗时: {end - start} 秒") |