欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python中time模塊的常用方法及應(yīng)用詳解

 更新時(shí)間:2025年03月19日 17:05:31   作者:傻啦嘿喲  
在Python開發(fā)中,時(shí)間處理是繞不開的剛需場(chǎng)景,從性能計(jì)時(shí)到定時(shí)任務(wù),從日志記錄到數(shù)據(jù)同步,時(shí)間模塊始終是開發(fā)者最得力的工具之一,本文將通過真實(shí)案例和簡(jiǎn)潔代碼,系統(tǒng)講解time模塊的6大核心方法及其典型應(yīng)用場(chǎng)景,需要的朋友可以參考下

一、時(shí)間基石:time.time()

time.time()是獲取時(shí)間戳的入口函數(shù),返回自1970年1月1日(Unix紀(jì) 元)以來的秒數(shù)(浮點(diǎn)數(shù))。這個(gè)10位數(shù)字像時(shí)間維度的身份證,是計(jì)算機(jī)世界的時(shí)間基準(zhǔn)。

典型場(chǎng)景:程序性能分析

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()  # 記錄開始時(shí)間戳
primes = calculate_prime(10000)
end_time = time.time()    # 記錄結(jié)束時(shí)間戳
 
print(f"耗時(shí):{end_time - start_time:.4f}秒")
# 輸出:耗時(shí):0.1234秒

進(jìn)階技巧:結(jié)合上下文管理器實(shí)現(xiàn)自動(dòng)計(jì)時(shí)

from contextlib import contextmanager
 
@contextmanager
def timer():
    start = time.time()
    yield
    print(f"耗時(shí):{time.time() - start:.4f}秒")
 
# 使用示例
with timer():
    data = [x**2 for x in range(1000000)]
# 輸出:耗時(shí):0.0456秒

二、時(shí)間暫停術(shù):time.sleep()

time.sleep(seconds)讓程序進(jìn)入休眠狀態(tài),參數(shù)支持浮點(diǎn)數(shù)實(shí)現(xiàn)毫秒級(jí)控制。這是實(shí)現(xiàn)定時(shí)任務(wù)、速率限制的核心方法。

典型場(chǎng)景:數(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)  # 每分鐘采集一次

注意事項(xiàng):

  • 實(shí)際休眠時(shí)間可能略長(zhǎng)于參數(shù)值(受系統(tǒng)調(diào)度影響)
  • 在GUI程序中需在獨(dú)立線程使用,避免界面凍結(jié)

三、時(shí)間格式化大師:time.strftime()

將時(shí)間戳轉(zhuǎn)換為可讀字符串,通過格式代碼自定義輸出樣式。這是日志記錄、數(shù)據(jù)展示的必備技能。

格式代碼速查表:

代碼    含義    示例

%Y    四位年份    2023

%m    月份(01-12)    09

%d    日期(01-31)    25

%H    小時(shí)(24制)    14

%M    分鐘    30

%S    秒    45

%f    微秒    123456

典型場(chǎng)景:生成標(biāo)準(zhǔn)化日志時(shí)間

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] 用戶登錄成功

四、時(shí)間差計(jì)算:time.perf_counter()

比time.time()更高精度的計(jì)時(shí)器,專為性能測(cè)量設(shè)計(jì)。返回包含小數(shù)秒的浮點(diǎn)數(shù),適合短時(shí)間間隔測(cè)量。

典型場(chǎng)景:算法性能對(duì)比

import time
 
def algorithm_a():
    # 算法A實(shí)現(xiàn)
    time.sleep(0.1)
 
def algorithm_b():
    # 算法B實(shí)現(xiàn)
    time.sleep(0.05)
 
start = time.perf_counter()
algorithm_a()
end = time.perf_counter()
print(f"算法A耗時(shí):{end - start:.6f}秒")
 
start = time.perf_counter()
algorithm_b()
end = time.perf_counter()
print(f"算法B耗時(shí):{end - start:.6f}秒")
# 輸出:
# 算法A耗時(shí):0.100234秒
# 算法B耗時(shí):0.050123秒

五、定時(shí)任務(wù)調(diào)度器

結(jié)合time.sleep()和循環(huán)結(jié)構(gòu),實(shí)現(xiàn)簡(jiǎn)單的定時(shí)任務(wù)系統(tǒng)。適用于輕量級(jí)后臺(tái)任務(wù)。

典型場(chǎng)景:定時(shí)數(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點(diǎn)執(zhí)行
        backup_data()
    time.sleep(3600)  # 每小時(shí)檢查一次

優(yōu)化方案:使用schedule庫(kù)實(shí)現(xiàn)更復(fù)雜的定時(shí)任務(wù)

import schedule
import time
 
def job():
    print("定時(shí)任務(wù)執(zhí)行")
 
# 每天10:30執(zhí)行
schedule.every().day.at("10:30").do(job)
 
while True:
    schedule.run_pending()
    time.sleep(60)

六、時(shí)間戳轉(zhuǎn)換實(shí)戰(zhàn)

time.localtime()和time.mktime()實(shí)現(xiàn)時(shí)間戳與結(jié)構(gòu)化時(shí)間的相互轉(zhuǎn)換,是數(shù)據(jù)持久化和網(wǎng)絡(luò)傳輸?shù)年P(guān)鍵環(huán)節(jié)。

典型場(chǎng)景:解析日志時(shí)間戳

import time
 
log_entry = "1695624645: ERROR - 數(shù)據(jù)庫(kù)連接失敗"
timestamp = int(log_entry.split(":")[0])
 
# 轉(zhuǎn)換為可讀時(shí)間
struct_time = time.localtime(timestamp)
readable_time = time.strftime("%Y-%m-%d %H:%M:%S", struct_time)
print(f"錯(cuò)誤發(fā)生時(shí)間:{readable_time}")
# 輸出:錯(cuò)誤發(fā)生時(shí)間:2023-09-25 14:30:45

反向轉(zhuǎn)換:將結(jié)構(gòu)化時(shí)間轉(zhuǎn)為時(shí)間戳

import time
 
# 創(chuàng)建結(jié)構(gòu)化時(shí)間
struct_time = time.strptime("2023-09-25 14:30:45", "%Y-%m-%d %H:%M:%S")
# 轉(zhuǎn)換為時(shí)間戳
timestamp = time.mktime(struct_time)
print(f"時(shí)間戳:{int(timestamp)}")
# 輸出:時(shí)間戳:1695624645

最佳實(shí)踐建議

  • 精度選擇:短時(shí)間測(cè)量用perf_counter(),長(zhǎng)時(shí)間間隔用time()
  • 時(shí)區(qū)處理:涉及多時(shí)區(qū)時(shí)優(yōu)先使用datetime模塊
  • 阻塞操作:在GUI或異步程序中避免直接使用sleep()
  • 日志記錄:始終包含時(shí)間戳信息
  • 性能監(jiān)控:結(jié)合time和logging模塊實(shí)現(xiàn)執(zhí)行時(shí)間追蹤

綜合案例:API調(diào)用速率限制

import time
import requests
 
class APIWrapper:
    def __init__(self, rate_limit=60):
        self.rate_limit = rate_limit  # 每分鐘最大請(qǐng)求數(shù)
        self.request_times = []
 
    def _check_rate_limit(self):
        current_time = time.time()
        # 清理過期記錄(保留最近1分鐘的請(qǐng)求)
        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)  # 額外緩沖時(shí)間
 
    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+實(shí)戰(zhàn)案例,開發(fā)者可以掌握時(shí)間處理的精髓。從基礎(chǔ)的時(shí)間戳操作到復(fù)雜的定時(shí)任務(wù)調(diào)度,time模塊始終是最可靠的伙伴。在實(shí)際開發(fā)中,建議結(jié)合具體場(chǎng)景選擇合適的方法,并注意時(shí)間精度、系統(tǒng)資源消耗等細(xì)節(jié)問題。

以上就是python中time模塊的常用方法及應(yīng)用詳解的詳細(xì)內(nèi)容,更多關(guān)于python time模塊方法及應(yīng)用的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論