# 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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。