当前位置: 代码网 > it编程>前端脚本>Python > python中time模块的常用方法及应用详解

python中time模块的常用方法及应用详解

2025年03月19日 Python 我要评论
一、时间基石:time.time()time.time()是获取时间戳的入口函数,返回自1970年1月1日(unix纪 元)以来的秒数(浮点数)。这个10位数字像时间维度的身份证,是计算机世界的时间基

一、时间基石:time.time()

time.time()是获取时间戳的入口函数,返回自1970年1月1日(unix纪 元)以来的秒数(浮点数)。这个10位数字像时间维度的身份证,是计算机世界的时间基准。

典型场景:程序性能分析

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()    # 记录结束时间戳
 
print(f"耗时:{end_time - start_time:.4f}秒")
# 输出:耗时:0.1234秒

进阶技巧:结合上下文管理器实现自动计时

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秒

二、时间暂停术:time.sleep()

time.sleep(seconds)让程序进入休眠状态,参数支持浮点数实现毫秒级控制。这是实现定时任务、速率限制的核心方法。

典型场景:数据采集间隔控制

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"获取数据:{len(data)}条")
    time.sleep(60)  # 每分钟采集一次

注意事项:

  • 实际休眠时间可能略长于参数值(受系统调度影响)
  • 在gui程序中需在独立线程使用,避免界面冻结

三、时间格式化大师:time.strftime()

将时间戳转换为可读字符串,通过格式代码自定义输出样式。这是日志记录、数据展示的必备技能。

格式代码速查表:

代码    含义    示例

%y    四位年份    2023

%m    月份(01-12)    09

%d    日期(01-31)    25

%h    小时(24制)    14

%m    分钟    30

%s    秒    45

%f    微秒    123456

典型场景:生成标准化日志时间

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()更高精度的计时器,专为性能测量设计。返回包含小数秒的浮点数,适合短时间间隔测量。

典型场景:算法性能对比

import time
 
def algorithm_a():
    # 算法a实现
    time.sleep(0.1)
 
def algorithm_b():
    # 算法b实现
    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秒

五、定时任务调度器

结合time.sleep()和循环结构,实现简单的定时任务系统。适用于轻量级后台任务。

典型场景:定时数据备份

import time
import shutil
 
def backup_data():
    shutil.copy("data.db", "backup/data_backup.db")
    print("数据备份完成")
 
while true:
    current_hour = time.localtime().tm_hour
    if current_hour == 2:  # 凌晨2点执行
        backup_data()
    time.sleep(3600)  # 每小时检查一次

优化方案:使用schedule库实现更复杂的定时任务

import schedule
import time
 
def job():
    print("定时任务执行")
 
# 每天10:30执行
schedule.every().day.at("10:30").do(job)
 
while true:
    schedule.run_pending()
    time.sleep(60)

六、时间戳转换实战

time.localtime()和time.mktime()实现时间戳与结构化时间的相互转换,是数据持久化和网络传输的关键环节。

典型场景:解析日志时间戳

import time
 
log_entry = "1695624645: error - 数据库连接失败"
timestamp = int(log_entry.split(":")[0])
 
# 转换为可读时间
struct_time = time.localtime(timestamp)
readable_time = time.strftime("%y-%m-%d %h:%m:%s", struct_time)
print(f"错误发生时间:{readable_time}")
# 输出:错误发生时间:2023-09-25 14:30:45

反向转换:将结构化时间转为时间戳

import time
 
# 创建结构化时间
struct_time = time.strptime("2023-09-25 14:30:45", "%y-%m-%d %h:%m:%s")
# 转换为时间戳
timestamp = time.mktime(struct_time)
print(f"时间戳:{int(timestamp)}")
# 输出:时间戳:1695624645

最佳实践建议

  • 精度选择:短时间测量用perf_counter(),长时间间隔用time()
  • 时区处理:涉及多时区时优先使用datetime模块
  • 阻塞操作:在gui或异步程序中避免直接使用sleep()
  • 日志记录:始终包含时间戳信息
  • 性能监控:结合time和logging模块实现执行时间追踪

综合案例:api调用速率限制

import time
import requests
 
class apiwrapper:
    def __init__(self, rate_limit=60):
        self.rate_limit = rate_limit  # 每分钟最大请求数
        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"速率限制触发,等待{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+实战案例,开发者可以掌握时间处理的精髓。从基础的时间戳操作到复杂的定时任务调度,time模块始终是最可靠的伙伴。在实际开发中,建议结合具体场景选择合适的方法,并注意时间精度、系统资源消耗等细节问题。

以上就是python中time模块的常用方法及应用详解的详细内容,更多关于python time模块方法及应用的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com