# 什么是Python time庫
## 概述
Python的`time`庫是標準庫中用于處理時間相關操作的核心模塊,提供了各種與時間獲取、格式轉換和程序控制相關的功能。作為與操作系統時間服務交互的接口,它能夠實現以下核心功能:
1. 獲取系統時間戳和結構化時間
2. 不同時間格式的相互轉換
3. 程序執行的時間控制
4. 時區相關的基礎處理
```python
import time
# 基礎示例:獲取當前時間戳
timestamp = time.time()
print("當前時間戳:", timestamp)
timestamp = time.time() # 輸出示例:1715587200.123456
local_time = time.localtime()
# 輸出:time.struct_time(tm_year=2023, tm_mon=6, tm_mday=15,...)
strftime(format[, t])方法:
- 支持20+格式指令(如%Y-年,%m-月)
- 常用格式:
time.strftime("%Y-%m-%d %H:%M:%S") # 輸出:2023-06-15 14:30:00
strptime(string, format)方法:
time_obj = time.strptime("2023-06-15", "%Y-%m-%d")
sleep(seconds)函數:
- 精確到毫秒級暫停
- 注意:會阻塞當前線程
print("開始")
time.sleep(2.5) # 暫停2.5秒
print("結束")
perf_counter()高精度計時器:
start = time.perf_counter()
# 執行代碼...
end = time.perf_counter()
print(f"耗時:{end-start:.2f}秒")
| 函數 | 描述 |
|---|---|
mktime(struct_time) |
本地時間 → 時間戳 |
gmtime([secs]) |
時間戳 → UTC struct_time |
ctime([secs]) |
時間戳 → 可讀字符串 |
# 時間戳與結構化時間互轉
struct_time = time.localtime(1715587200)
timestamp = time.mktime(struct_time)
def log(message):
now = time.strftime("[%Y-%m-%d %H:%M:%S]")
print(f"{now} {message}")
while True:
do_something()
time.sleep(3600) # 每小時執行一次
timeout = 5
start = time.time()
while condition_not_met():
if time.time() - start > timeout:
raise TimeoutError
time.sleep(0.1)
時區問題:
pytz庫精度差異:
替代方案:
datetime:高級日期處理calendar:日歷相關功能import time
def countdown(seconds):
"""倒計時器"""
for i in range(seconds, 0, -1):
print(f"\r剩余時間:{i}秒", end="")
time.sleep(1)
print("\n時間到!")
def format_demo():
"""格式化演示"""
now = time.localtime()
print("24小時制:", time.strftime("%Y-%m-%d %H:%M:%S", now))
print("12小時制:", time.strftime("%Y-%m-%d %I:%M:%S %p", now))
if __name__ == "__main__":
countdown(5)
format_demo()
Python的time庫作為時間處理的基礎工具,具有以下特點: - 輕量級:無需安裝,即導即用 - 多功能:覆蓋時間處理的常見需求 - 跨平臺:在不同操作系統表現一致
對于更復雜的時間操作,建議結合datetime和第三方庫使用,但對于大多數基礎時間操作,time庫仍然是高效簡潔的選擇。
“`
注:實際字符數約為1250字(含代碼和格式標記)。如需調整內容長度,可增減示例部分或擴展注意事項章節。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。