您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Python中时间操作time怎么用
## 目录
1. [time模块概述](#time模块概述)
2. [时间戳操作](#时间戳操作)
3. [时间格式化](#时间格式化)
4. [结构化时间](#结构化时间)
5. [延时与计时](#延时与计时)
6. [性能测量](#性能测量)
7. [时区处理](#时区处理)
8. [常见问题与解决方案](#常见问题与解决方案)
9. [总结](#总结)
---
## time模块概述
Python的`time`模块是处理时间相关操作的核心模块之一,提供了各种时间相关的函数。该模块主要包含三类时间表示形式:
- **时间戳(Timestamp)**:从1970年1月1日00:00:00开始的秒数(浮点数)
- **结构化时间(struct_time)**:包含9个元素的元组
- **格式化时间(Formatted String)**:可读的字符串形式
```python
import time
current_timestamp = time.time()
print(f"当前时间戳: {current_timestamp}")
# 输出示例: 1689987600.123456
# 时间戳 → 结构化时间
local_struct = time.localtime(current_timestamp)
gm_struct = time.gmtime(current_timestamp)
# 结构化时间 → 时间戳
new_timestamp = time.mktime(local_struct)
# 默认格式
formatted_time = time.ctime(current_timestamp)
# 输出: "Mon Jul 24 15:30:00 2023"
# 自定义格式
custom_format = time.strftime("%Y-%m-%d %H:%M:%S", local_struct)
# 输出: "2023-07-24 15:30:00"
time_str = "2023-07-24"
parsed_struct = time.strptime(time_str, "%Y-%m-%d")
符号 | 含义 | 示例 |
---|---|---|
%Y |
四位年份 | 2023 |
%m |
月份(01-12) | 07 |
%d |
日期(01-31) | 24 |
%H |
24小时制小时 | 15 |
%M |
分钟(00-59) | 30 |
%S |
秒(00-59) | 45 |
%A |
星期全名 | Monday |
struct_time对象的9个属性:
time.struct_time(
tm_year=2023, # 年
tm_mon=7, # 月
tm_mday=24, # 日
tm_hour=15, # 时
tm_min=30, # 分
tm_sec=45, # 秒
tm_wday=0, # 星期(0-6)
tm_yday=205, # 一年中的第几天
tm_isdst=0 # 夏令时标志
)
year = local_struct.tm_year
hour = local_struct.tm_hour
print("开始执行")
time.sleep(2.5) # 暂停2.5秒
print("延迟结束")
start = time.perf_counter() # 高精度计时器
# 执行代码...
end = time.perf_counter()
print(f"耗时: {end - start:.4f}秒")
def test_func():
time.sleep(0.1)
# 方法1: time.time()
start = time.time()
test_func()
print(f"time.time(): {time.time() - start:.6f}")
# 方法2: time.perf_counter()
start = time.perf_counter()
test_func()
print(f"perf_counter: {time.perf_counter() - start:.6f}")
虽然time模块原生不支持时区,但可以结合其他模块处理:
import time
from datetime import datetime, timezone
# 获取UTC时间
utc_time = time.gmtime()
print(time.strftime("%Y-%m-%d %H:%M:%S UTC", utc_time))
# 本地时区转换
local_time = time.localtime()
print(time.strftime("%Y-%m-%d %H:%M:%S %Z", local_time))
# Windows系统默认精度约15ms
timestamp = time.time() # 可能返回1689987600.123
# 解决方案:使用perf_counter
high_res = time.perf_counter()
# 不同系统sleep精度不同
time.sleep(0.001) # 实际可能休眠更长时间
# 替代方案:busy waiting(仅适用于极短延时)
def precise_sleep(duration):
end = time.perf_counter() + duration
while time.perf_counter() < end:
pass
# 错误示例:直接比较不同时区时间
utc_time = time.gmtime()
local_time = time.localtime()
# 正确做法:统一转换为UTC比较
utc_timestamp = time.mktime(utc_time) - time.timezone
local_timestamp = time.mktime(local_time)
核心功能:
time.time()
strftime()
/strptime()
localtime()
/gmtime()
性能工具:
time.time()
time.perf_counter()
time.process_time()
最佳实践:
datetime
模块perf_counter
signal.alarm
完整代码示例见下方:
import time
def time_operations_demo():
# 获取当前时间
now = time.time()
print(f"Timestamp: {now}")
# 转换为本地时间
local = time.localtime(now)
print(f"Local struct: {local}")
# 格式化输出
formatted = time.strftime("%Y-%m-%d %H:%M:%S", local)
print(f"Formatted: {formatted}")
# 计时示例
start = time.perf_counter()
time.sleep(0.5)
duration = time.perf_counter() - start
print(f"Slept for: {duration:.6f} seconds")
time_operations_demo()
通过掌握这些核心功能,您已经能够处理Python中大多数时间相关的操作需求。 “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。