time.time()是获取时间戳的入口函数,返回自1970年1月1日(Unix纪 元)以来的秒数(浮点数)。这个10位数字像时间维度的身份证,是计算机世界的时间基准。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
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秒 |
1 2 3 4 5 6 7 8 9 10 11 12 |
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(seconds)让程序进入休眠状态,参数支持浮点数实现毫秒级控制。这是实现定时任务、速率限制的核心方法。
1 2 3 4 5 6 7 8 9 10 11 |
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) # 每分钟采集一次 |
注意事项:
将时间戳转换为可读字符串,通过格式代码自定义输出样式。这是日志记录、数据展示的必备技能。
格式代码速查表:
代码 含义 示例
%Y 四位年份 2023
%m 月份(01-12) 09
%d 日期(01-31) 25
%H 小时(24制) 14
%M 分钟 30
%S 秒 45
%f 微秒 123456
1 2 3 4 5 6 7 8 |
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.time()更高精度的计时器,专为性能测量设计。返回包含小数秒的浮点数,适合短时间间隔测量。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
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()和循环结构,实现简单的定时任务系统。适用于轻量级后台任务。
1 2 3 4 5 6 7 8 9 10 11 12 |
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) # 每小时检查一次 |
1 2 3 4 5 6 7 8 9 10 11 12 |
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()实现时间戳与结构化时间的相互转换,是数据持久化和网络传输的关键环节。
1 2 3 4 5 6 7 8 9 10 |
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 |
1 2 3 4 5 6 7 8 |
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 |
最佳实践建议
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
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模块始终是最可靠的伙伴。在实际开发中,建议结合具体场景选择合适的方法,并注意时间精度、系统资源消耗等细节问题。