当前位置:首页 > Python > 正文

Python time模块详解 - 时间处理完全指南

Python time模块详解

全面掌握Python时间处理的核心工具

在Python编程中,处理时间是一项常见且重要的任务。Python内置的time模块提供了各种与时间相关的函数,能够帮助开发者获取当前时间、格式化时间、测量代码执行时间以及进行时间转换等操作。本教程将深入解析time模块的核心功能和使用方法。

time模块基础功能

time模块提供了一系列处理时间的函数,以下是其主要功能分类:

功能类别 常用函数 描述
时间获取 time(), ctime(), gmtime(), localtime() 获取当前时间戳、可读时间字符串、结构化时间对象
时间格式化 strftime(), strptime() 时间对象与字符串之间的相互转换
时间操作 mktime(), asctime() 时间对象与时间戳的转换
计时功能 sleep(), perf_counter(), process_time() 程序暂停、精确计时和进程时间测量

时间获取函数详解

1. time.time() - 获取当前时间戳

返回自纪元(1970年1月1日00:00:00 UTC)以来的秒数,浮点数形式。

import time # 获取当前时间戳 timestamp = time.time() print(f"当前时间戳: {timestamp}")

2. time.ctime() - 可读时间字符串

将时间戳转换为可读的本地时间字符串,默认使用当前时间。

# 获取当前时间的可读字符串 current_time = time.ctime() print(f"当前时间: {current_time}") # 转换特定时间戳 timestamp = 1689876543.21 converted_time = time.ctime(timestamp) print(f"转换后的时间: {converted_time}")

3. time.localtime() - 本地结构化时间

返回表示本地时间的struct_time对象,包含年、月、日等详细信息。

# 获取本地时间的结构化对象 local_time = time.localtime() print("本地结构化时间:") print(f" 年份: {local_time.tm_year}") print(f" 月份: {local_time.tm_mon}") print(f" 日期: {local_time.tm_mday}") print(f" 小时: {local_time.tm_hour}") print(f" 分钟: {local_time.tm_min}") print(f" 星期: {local_time.tm_wday + 1}") # 0-6 (周一为0)

当前时间可视化

Loading time...
Timestamp:

时间格式化与解析

1. time.strftime() - 时间格式化

将struct_time对象格式化为指定格式的字符串。

# 格式化当前时间 formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print(f"格式化时间: {formatted_time}") # 更多格式示例 print(time.strftime("%A, %d %B %Y")) # 星期, 日 月 年 print(time.strftime("Today is %j day of the year")) # 一年中的第几天
常用格式代码:
%Y - 四位数年份 (2023)
%m - 月份 (01-12)
%d - 日期 (01-31)
%H - 24小时制小时 (00-23)
%M - 分钟 (00-59)
%S - 秒 (00-59)
%A - 完整星期名称 (Monday)
%B - 完整月份名称 (January)

2. time.strptime() - 时间解析

将时间字符串解析为struct_time对象。

# 解析时间字符串 time_str = "2023-07-20 14:30:00" parsed_time = time.strptime(time_str, "%Y-%m-%d %H:%M:%S") print("解析后的时间对象:") print(f" 年份: {parsed_time.tm_year}") print(f" 月份: {parsed_time.tm_mon}") print(f" 日期: {parsed_time.tm_mday}")

时间转换与操作

1. time.mktime() - 转换为时间戳

将struct_time对象转换为时间戳。

# 创建struct_time对象 time_tuple = (2023, 7, 20, 14, 30, 0, 0, 0, 0) # 转换为时间戳 timestamp = time.mktime(time_tuple) print(f"转换后的时间戳: {timestamp}")

2. time.gmtime() - UTC时间

获取当前UTC时间的struct_time对象。

# 获取UTC时间 utc_time = time.gmtime() print("UTC时间:") print(f" {utc_time.tm_hour}:{utc_time.tm_min}:{utc_time.tm_sec}")
时区转换示例

将本地时间转换为UTC时间并计算时间差:

# 获取本地时间和UTC时间 local_time = time.localtime() utc_time = time.gmtime() # 计算时区偏移(小时) timezone_offset = local_time.tm_hour - utc_time.tm_hour if timezone_offset < 0: timezone_offset += 24 print(f"本地时间与UTC时间相差 {timezone_offset} 小时")

计时与性能测量

1. time.sleep() - 程序暂停

使程序暂停执行指定的秒数。

print("程序开始执行...") time.sleep(2.5) # 暂停2.5秒 print("2.5秒后继续执行")

2. 性能测量方法

time模块提供了多种测量时间的方法:

# 使用time.time()测量 start_time = time.time() # 执行一些操作 time.sleep(1.5) end_time = time.time() print(f"执行时间: {end_time - start_time:.4f} 秒") # 使用time.perf_counter() (更高精度) start = time.perf_counter() time.sleep(0.75) end = time.perf_counter() print(f"高精度执行时间: {end - start:.6f} 秒") # 使用time.process_time() (测量CPU时间) start_cpu = time.process_time() # 执行CPU密集型操作 sum(range(1000000)) end_cpu = time.process_time() print(f"CPU处理时间: {end_cpu - start_cpu:.6f} 秒")
性能测量建议:
• 对于一般代码计时,使用time.perf_counter()
• 测量CPU处理时间,使用time.process_time()
• 需要跨平台兼容性,使用time.time()
• 避免在性能测量中使用time.sleep()

实际应用案例

案例1:程序运行时间统计
def calculate_sum(n): """计算1到n的和""" return sum(range(1, n+1)) # 记录开始时间 start_time = time.perf_counter() # 执行函数 result = calculate_sum(1000000) # 记录结束时间 end_time = time.perf_counter() # 计算并显示执行时间 elapsed = end_time - start_time print(f"计算结果: {result}") print(f"执行时间: {elapsed:.6f} 秒")
案例2:倒计时定时器
def countdown(seconds): """倒计时函数""" while seconds: mins, secs = divmod(seconds, 60) time_format = f"{mins:02d}:{secs:02d}" print(time_format, end='\r') time.sleep(1) seconds -= 1 print("时间到!") # 开始10秒倒计时 countdown(10)
案例3:时间戳转换工具
def timestamp_to_date(ts=None): """将时间戳转换为可读日期""" if ts is None: ts = time.time() return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts)) # 转换当前时间戳 print(f"当前时间: {timestamp_to_date()}") # 转换指定时间戳 print(f"指定时间: {timestamp_to_date(1609459200)}") # 2021-01-01 00:00:00

发表评论