python中time模塊的常用方法及應(yīng)用詳解
一、時間基石:time.time()
time.time()是獲取時間戳的入口函數(shù),返回自1970年1月1日(Unix紀(jì) 元)以來的秒數(shù)(浮點數(shù))。這個10位數(shù)字像時間維度的身份證,是計算機(jī)世界的時間基準(zhǔn)。
典型場景:程序性能分析
import time def calculate_prime(n): primes = [] for num in range(2, n): is_prime = True for i in range(2, int(num**0.5)+1): if num % i == 0: is_prime = False break if is_prime: primes.append(num) return primes start_time = time.time() # 記錄開始時間戳 primes = calculate_prime(10000) end_time = time.time() # 記錄結(jié)束時間戳 print(f"耗時:{end_time - start_time:.4f}秒") # 輸出:耗時:0.1234秒
進(jìn)階技巧:結(jié)合上下文管理器實現(xiàn)自動計時
from contextlib import contextmanager @contextmanager def timer(): start = time.time() yield print(f"耗時:{time.time() - start:.4f}秒") # 使用示例 with timer(): data = [x**2 for x in range(1000000)] # 輸出:耗時:0.0456秒
二、時間暫停術(shù):time.sleep()
time.sleep(seconds)讓程序進(jìn)入休眠狀態(tài),參數(shù)支持浮點數(shù)實現(xiàn)毫秒級控制。這是實現(xiàn)定時任務(wù)、速率限制的核心方法。
典型場景:數(shù)據(jù)采集間隔控制
import time import requests def fetch_data(): response = requests.get("https://api.example.com/data") return response.json() while True: data = fetch_data() print(f"獲取數(shù)據(jù):{len(data)}條") time.sleep(60) # 每分鐘采集一次
注意事項:
- 實際休眠時間可能略長于參數(shù)值(受系統(tǒng)調(diào)度影響)
- 在GUI程序中需在獨立線程使用,避免界面凍結(jié)
三、時間格式化大師:time.strftime()
將時間戳轉(zhuǎn)換為可讀字符串,通過格式代碼自定義輸出樣式。這是日志記錄、數(shù)據(jù)展示的必備技能。
格式代碼速查表:
代碼 含義 示例
%Y 四位年份 2023
%m 月份(01-12) 09
%d 日期(01-31) 25
%H 小時(24制) 14
%M 分鐘 30
%S 秒 45
%f 微秒 123456
典型場景:生成標(biāo)準(zhǔn)化日志時間
import time def log(message): timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print(f"[{timestamp}] {message}") log("用戶登錄成功") # 輸出:[2023-09-25 14:30:45] 用戶登錄成功
四、時間差計算:time.perf_counter()
比time.time()更高精度的計時器,專為性能測量設(shè)計。返回包含小數(shù)秒的浮點數(shù),適合短時間間隔測量。
典型場景:算法性能對比
import time def algorithm_a(): # 算法A實現(xiàn) time.sleep(0.1) def algorithm_b(): # 算法B實現(xiàn) time.sleep(0.05) start = time.perf_counter() algorithm_a() end = time.perf_counter() print(f"算法A耗時:{end - start:.6f}秒") start = time.perf_counter() algorithm_b() end = time.perf_counter() print(f"算法B耗時:{end - start:.6f}秒") # 輸出: # 算法A耗時:0.100234秒 # 算法B耗時:0.050123秒
五、定時任務(wù)調(diào)度器
結(jié)合time.sleep()和循環(huán)結(jié)構(gòu),實現(xiàn)簡單的定時任務(wù)系統(tǒng)。適用于輕量級后臺任務(wù)。
典型場景:定時數(shù)據(jù)備份
import time import shutil def backup_data(): shutil.copy("data.db", "backup/data_backup.db") print("數(shù)據(jù)備份完成") while True: current_hour = time.localtime().tm_hour if current_hour == 2: # 凌晨2點執(zhí)行 backup_data() time.sleep(3600) # 每小時檢查一次
優(yōu)化方案:使用schedule庫實現(xiàn)更復(fù)雜的定時任務(wù)
import schedule import time def job(): print("定時任務(wù)執(zhí)行") # 每天10:30執(zhí)行 schedule.every().day.at("10:30").do(job) while True: schedule.run_pending() time.sleep(60)
六、時間戳轉(zhuǎn)換實戰(zhàn)
time.localtime()和time.mktime()實現(xiàn)時間戳與結(jié)構(gòu)化時間的相互轉(zhuǎn)換,是數(shù)據(jù)持久化和網(wǎng)絡(luò)傳輸?shù)年P(guān)鍵環(huán)節(jié)。
典型場景:解析日志時間戳
import time log_entry = "1695624645: ERROR - 數(shù)據(jù)庫連接失敗" timestamp = int(log_entry.split(":")[0]) # 轉(zhuǎn)換為可讀時間 struct_time = time.localtime(timestamp) readable_time = time.strftime("%Y-%m-%d %H:%M:%S", struct_time) print(f"錯誤發(fā)生時間:{readable_time}") # 輸出:錯誤發(fā)生時間:2023-09-25 14:30:45
反向轉(zhuǎn)換:將結(jié)構(gòu)化時間轉(zhuǎn)為時間戳
import time # 創(chuàng)建結(jié)構(gòu)化時間 struct_time = time.strptime("2023-09-25 14:30:45", "%Y-%m-%d %H:%M:%S") # 轉(zhuǎn)換為時間戳 timestamp = time.mktime(struct_time) print(f"時間戳:{int(timestamp)}") # 輸出:時間戳:1695624645
最佳實踐建議
- 精度選擇:短時間測量用perf_counter(),長時間間隔用time()
- 時區(qū)處理:涉及多時區(qū)時優(yōu)先使用datetime模塊
- 阻塞操作:在GUI或異步程序中避免直接使用sleep()
- 日志記錄:始終包含時間戳信息
- 性能監(jiān)控:結(jié)合time和logging模塊實現(xiàn)執(zhí)行時間追蹤
綜合案例:API調(diào)用速率限制
import time import requests class APIWrapper: def __init__(self, rate_limit=60): self.rate_limit = rate_limit # 每分鐘最大請求數(shù) self.request_times = [] def _check_rate_limit(self): current_time = time.time() # 清理過期記錄(保留最近1分鐘的請求) self.request_times = [t for t in self.request_times if current_time - t < 60] if len(self.request_times) >= self.rate_limit: oldest = self.request_times[0] wait_time = 60 - (current_time - oldest) print(f"速率限制觸發(fā),等待{wait_time:.2f}秒") time.sleep(wait_time + 0.1) # 額外緩沖時間 def get(self, url): self._check_rate_limit() response = requests.get(url) self.request_times.append(time.time()) return response # 使用示例 api = APIWrapper(rate_limit=60) response = api.get("https://api.example.com/data") print(response.status_code)
通過本文的6大核心方法和10+實戰(zhàn)案例,開發(fā)者可以掌握時間處理的精髓。從基礎(chǔ)的時間戳操作到復(fù)雜的定時任務(wù)調(diào)度,time模塊始終是最可靠的伙伴。在實際開發(fā)中,建議結(jié)合具體場景選擇合適的方法,并注意時間精度、系統(tǒng)資源消耗等細(xì)節(jié)問題。
以上就是python中time模塊的常用方法及應(yīng)用詳解的詳細(xì)內(nèi)容,更多關(guān)于python time模塊方法及應(yīng)用的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python+selenium+autoit實現(xiàn)文件上傳功能
這篇文章主要介紹了python+selenium+autoit實現(xiàn)文件上傳功能,需要的朋友可以參考下2017-08-08Python使用APScheduler實現(xiàn)定時任務(wù)過程解析
這篇文章主要介紹了Python使用APScheduler實現(xiàn)定時任務(wù)過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-09-09Python腳本簡單實現(xiàn)打開默認(rèn)瀏覽器登錄人人和打開QQ的方法
這篇文章主要介紹了Python腳本簡單實現(xiàn)打開默認(rèn)瀏覽器登錄人人和打開QQ的方法,涉及Python針對瀏覽器及應(yīng)用程序的相關(guān)操作技巧,代碼非常簡單實用,需要的朋友可以參考下2016-04-04Python利用pyodbc庫將文件信息插入Access數(shù)據(jù)庫
在日常編程工作中,我們經(jīng)常需要處理文件和文件夾,所以本文將介紹如何使用Python編程語言和wxPython庫創(chuàng)建一個簡單的文件瀏覽器界面,使用戶能夠選擇文件夾并將文件信息插入到Access數(shù)據(jù)庫中,需要的可以參考下2023-08-08python輕松辦公將100個Excel中符合條件的數(shù)據(jù)匯總到1個Excel里
這篇文章主要為大家介紹了python輕松辦公將100個Excel中符合條件的數(shù)據(jù)匯總到1個Excel里示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03