Python 的时间处理主要依赖于time、datetime和calendar三大标准库模块它们分别用于底层时间操作、高级日期时间处理以及日历相关功能。一、time模块底层时间接口time模块提供与系统时间相关的函数核心是处理时间戳和struct_time元组。1. 核心概念与转换时间戳Timestamp是自1970年1月1日00:00:00 UTC纪元以来的秒数浮点数。struct_time是一个包含9个元素的元组用于表示本地时间。import time # 1. 获取当前时间戳 timestamp time.time() print(f当前时间戳: {timestamp}) # 例如1715589123.456 # 2. 时间戳 - struct_time (本地时间) local_struct time.localtime(timestamp) print(f本地struct_time: {local_struct}) # 输出time.struct_time(tm_year2024, tm_mon5, tm_mday12, ...) # 3. 时间戳 - struct_time (UTC时间) utc_struct time.gmtime(timestamp) print(fUTC struct_time: {utc_struct}) # 4. struct_time - 时间戳 timestamp_from_struct time.mktime(local_struct) print(f从struct_time转换回的时间戳: {timestamp_from_struct}) # 5. struct_time - 格式化字符串 formatted_str time.strftime(%Y-%m-%d %H:%M:%S, local_struct) print(f格式化后的时间字符串: {formatted_str}) # 输出2024-05-12 15:12:03 # 6. 格式化字符串 - struct_time parsed_struct time.strptime(2024-05-12 15:12:03, %Y-%m-%d %H:%M:%S) print(f从字符串解析的struct_time: {parsed_struct})2.struct_time元组详解struct_time的9个字段含义如下表所示索引属性值范围说明0tm_year例如 2024年份1tm_mon1-12月份2tm_mday1-31月份中的第几天3tm_hour0-23小时4tm_min0-59分钟5tm_sec0-61 (60, 61是闰秒)秒6tm_wday0-6 (0是周一)一周中的第几天7tm_yday1-366一年中的第几天8tm_isdst-1, 0, 1夏令时标志 (-1表示未知)可以通过属性名或索引访问t time.localtime() print(f年份: {t.tm_year}) # 通过属性访问 print(f月份: {t[1]}) # 通过索引访问3. 常用函数与休眠import time # 1. 获取可读时间字符串 readable_time time.ctime() # 或 time.asctime() print(f可读时间: {readable_time}) # 输出Sun May 12 15:12:03 2024 # 2. 程序休眠 (单位秒) print(开始休眠2.5秒...) time.sleep(2.5) print(休眠结束) # 3. 性能计时 (用于简单基准测试) start time.perf_counter() # 高精度计时器 # 执行一些操作 time.sleep(0.1) end time.perf_counter() print(f操作耗时: {end - start:.6f} 秒)二、datetime模块高级日期时间处理datetime模块提供了更高级、更易用的日期时间类是日常开发中最常用的时间模块。1. 核心类与创建主要包含date、time、datetime、timedelta和tzinfo类。from datetime import datetime, date, time, timedelta import time as tmodule # 1. 获取当前日期和时间 now datetime.now() print(f当前日期时间: {now}) # 输出2024-05-12 15:12:03.456789 today date.today() print(f当前日期: {today}) # 输出2024-05-12 # 2. 创建特定日期时间 # 方式1: 直接构造 dt1 datetime(2024, 5, 12, 15, 30, 0) print(f构造的datetime: {dt1}) # 方式2: 从时间戳创建 dt_from_timestamp datetime.fromtimestamp(tmodule.time()) print(f从时间戳创建: {dt_from_timestamp}) # 方式3: 从字符串解析 (推荐使用) dt_from_str datetime.strptime(2024-05-12 15:30:00, %Y-%m-%d %H:%M:%S) print(f从字符串解析: {dt_from_str}) # 3. 创建date和time对象 d date(2024, 5, 12) print(f日期对象: {d}) t time(15, 30, 0) print(f时间对象: {t})2. 时间运算与差值timedelta表示两个日期时间之间的差值支持加减运算。from datetime import datetime, timedelta now datetime.now() # 1. 基本时间运算 one_day timedelta(days1) one_hour timedelta(hours1) one_week timedelta(weeks1) tomorrow now one_day yesterday now - one_day next_hour now one_hour print(f现在: {now}) print(f明天: {tomorrow}) print(f昨天: {yesterday}) print(f一小时后: {next_hour}) # 2. 复杂时间运算 future now timedelta(days7, hours3, minutes30) past now - timedelta(weeks2, days1) # 3. 计算时间差 dt1 datetime(2024, 5, 1, 10, 0, 0) dt2 datetime(2024, 5, 12, 15, 30, 0) delta dt2 - dt1 print(f时间差: {delta}) # 输出11 days, 5:30:00 print(f相差天数: {delta.days}) # 输出11 print(f相差秒数: {delta.seconds}) # 输出19800 (5小时30分钟) print(f总相差秒数: {delta.total_seconds()}) # 输出966600.03. 格式化与属性访问from datetime import datetime now datetime.now() # 1. 格式化输出 formatted now.strftime(%Y年%m月%d日 %H时%M分%S秒) print(f自定义格式化: {formatted}) # 输出2024年05月12日 15时12分03秒 # 2. 常用格式化符号对照表 format_codes { %Y: 四位数的年份 (2024), %y: 两位数的年份 (24), %m: 月份 (01-12), %d: 月内中的一天 (01-31), %H: 24小时制小时数 (00-23), %I: 12小时制小时数 (01-12), %M: 分钟数 (00-59), %S: 秒数 (00-59), %A: 星期几的全称 (Sunday), %a: 星期几的简写 (Sun), %B: 月份的全称 (May), %b: 月份的简写 (May), %p: AM或PM, %j: 年内的一天 (001-366), %U: 年内第几周 (周日为一周起始), %W: 年内第几周 (周一为一周起始) } # 3. 访问各个属性 print(f年份: {now.year}) print(f月份: {now.month}) print(f日期: {now.day}) print(f小时: {now.hour}) print(f分钟: {now.minute}) print(f秒: {now.second}) print(f微秒: {now.microsecond}) print(f星期几 (周一为0): {now.weekday()}) # 0-6 print(f星期几 (ISO标准): {now.isoweekday()}) # 1-7 (1为周一) # 4. 转换为时间戳 timestamp now.timestamp() print(f对应的时间戳: {timestamp})三、calendar模块日历相关功能calendar模块提供与日历相关的功能如生成月历、判断闰年等。import calendar from datetime import date # 1. 生成月历 may_2024 calendar.month(2024, 5) print(f2024年5月的月历: {may_2024}) # 输出 # May 2024 # Mo Tu We Th Fr Sa Su # 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 29 30 31 # 2. 生成年历 year_2024 calendar.calendar(2024, w2, l1, c6) # w: 日期列宽, l: 每周行数, c: 月份间隔 print(f2024年年历 (前3个月): {year_2024[:500]}...) # 3. 实用函数 year 2024 month 2 # 判断闰年 is_leap calendar.isleap(year) print(f{year}年是闰年吗? {is_leap}) # 2024年是闰年 # 获取某月的第一天是星期几和该月的天数 first_weekday, month_days calendar.monthrange(year, month) print(f{year}年{month}月: 第一天是星期{first_weekday} (0周一), 共有{month_days}天) # 获取某月日历矩阵 (列表的列表) month_matrix calendar.monthcalendar(year, month) print(f{year}年{month}月的日历矩阵: {month_matrix}) # 4. 计算特定日期是星期几 target_date date(2024, 5, 12) weekday_num target_date.weekday() # 0周一, 6周日 weekday_name calendar.day_name[weekday_num] print(f{target_date} 是 {weekday_name})四、timeit模块代码执行时间测量timeit模块专门用于测量小段代码的执行时间比手动使用time.time()更准确。import timeit import random # 1. 基本用法测量单条语句执行时间 # 测量列表推导式的执行时间 list_comp_time timeit.timeit([x**2 for x in range(1000)], number10000) print(f列表推导式执行10000次耗时: {list_comp_time:.4f} 秒) # 2. 测量函数执行时间 def test_function(): return sum([i**2 for i in range(1000)]) func_time timeit.timeit(test_function, number5000) print(f函数执行5000次耗时: {func_time:.4f} 秒) # 3. 使用Timer类进行更精细的控制 setup_code import random data [random.random() for _ in range(1000)] test_code sorted_data sorted(data) timer timeit.Timer(stmttest_code, setupsetup_code) # 执行3轮每轮重复1000次 results timer.repeat(repeat3, number1000) print(f排序操作计时结果: {results}) print(f最佳时间: {min(results):.6f} 秒) # 4. 在命令行中使用timeit # python -m timeit [x**2 for x in range(1000)] # python -m timeit -s import random sorted([random.random() for _ in range(100)]) # 5. 比较不同实现的性能 def method1(): result [] for i in range(1000): result.append(i**2) return result def method2(): return [i**2 for i in range(1000)] # 测量两种方法 time1 timeit.timeit(method1, number5000) time2 timeit.timeit(method2, number5000) print(f方法1 (for循环): {time1:.4f} 秒) print(f方法2 (列表推导式): {time2:.4f} 秒) print(f性能提升: {(time1-time2)/time1*100:.1f}%)五、综合应用场景与示例场景1日志文件按时间命名和轮转from datetime import datetime, timedelta import os def create_timestamped_log(): 创建带时间戳的日志文件 # 生成时间戳字符串 timestamp datetime.now().strftime(%Y%m%d_%H%M%S) log_filename fapp_{timestamp}.log # 创建日志文件 with open(log_filename, w) as f: f.write(f日志创建于: {datetime.now()} ) print(f已创建日志文件: {log_filename}) return log_filename def cleanup_old_logs(directory, days_to_keep7): 清理超过指定天数的旧日志文件 cutoff_time datetime.now() - timedelta(daysdays_to_keep) for filename in os.listdir(directory): if filename.startswith(app_) and filename.endswith(.log): # 从文件名中解析时间 try: # 格式: app_20240512_151203.log time_str filename[4:-4] # 移除app_和.log file_time datetime.strptime(time_str, %Y%m%d_%H%M%S) if file_time cutoff_time: filepath os.path.join(directory, filename) os.remove(filepath) print(f已删除旧日志: {filename}) except ValueError: continue # 使用示例 log_file create_timestamped_log() # 假设每天执行一次清理 cleanup_old_logs(., days_to_keep30)场景2任务调度与超时控制import time from datetime import datetime, timedelta import threading def long_running_task(task_id, duration): 模拟长时间运行的任务 print(f[{datetime.now()}] 任务 {task_id} 开始预计耗时 {duration} 秒) time.sleep(duration) print(f[{datetime.now()}] 任务 {task_id} 完成) return f任务 {task_id} 结果 def run_with_timeout(func, args, timeout): 带超时限制执行函数 result [None] exception [None] def worker(): try: result[0] func(*args) except Exception as e: exception[0] e thread threading.Thread(targetworker) thread.start() thread.join(timeout) if thread.is_alive(): print(f函数执行超时 (限制: {timeout}秒)) return None elif exception[0] is not None: print(f函数执行出错: {exception[0]}) return None else: return result[0] # 使用示例 start_time datetime.now() print(f程序开始于: {start_time}) # 执行带超时的任务 task_result run_with_timeout(long_running_task, (1, 5), 3) # 任务需5秒超时设为3秒 print(f任务结果: {task_result}) # 计算总耗时 end_time datetime.now() total_duration (end_time - start_time).total_seconds() print(f程序总耗时: {total_duration:.2f} 秒)场景3生日提醒系统from datetime import datetime, date, timedelta class BirthdayReminder: def __init__(self): self.birthdays [] def add_birthday(self, name, year, month, day): 添加生日 self.birthdays.append({ name: name, birthday: date(year, month, day) }) def get_upcoming_birthdays(self, days_ahead30): 获取未来指定天数内的生日 today date.today() upcoming [] for person in self.birthdays: # 计算今年的生日 birthday_this_year date(today.year, person[birthday].month, person[birthday].day) # 如果今年的生日已过计算明年的生日 if birthday_this_year today: birthday_this_year date(today.year 1, person[birthday].month, person[birthday].day) # 计算距离今天的天数 days_until (birthday_this_year - today).days if 0 days_until days_ahead: upcoming.append({ name: person[name], birthday: birthday_this_year, days_until: days_until, weekday: birthday_this_year.strftime(%A) }) # 按距离排序 upcoming.sort(keylambda x: x[days_until]) return upcoming def get_age_on_birthday(self, name, target_yearNone): 计算在目标年份生日时的年龄 if target_year is None: target_year date.today().year for person in self.birthdays: if person[name] name: birth_year person[birthday].year age target_year - birth_year return age return None # 使用示例 reminder BirthdayReminder() reminder.add_birthday(张三, 1990, 5, 15) reminder.add_birthday(李四, 1985, 5, 20) reminder.add_birthday(王五, 1995, 6, 10) # 获取未来30天的生日提醒 upcoming reminder.get_upcoming_birthdays(30) print(未来30天内的生日:) for person in upcoming: print(f {person[name]}: {person[birthday]} ({person[weekday]}), 还有{person[days_until]}天) # 计算年龄 age reminder.get_age_on_birthday(张三, 2024) print(f张三在2024年生日时的年龄: {age}岁)场景4性能监控装饰器import time import timeit from functools import wraps from datetime import datetime def performance_monitor(func): 性能监控装饰器 wraps(func) def wrapper(*args, **kwargs): # 使用time.perf_counter()获取高精度时间 start_time time.perf_counter() start_datetime datetime.now() try: result func(*args, **kwargs) finally: end_time time.perf_counter() elapsed end_time - start_time # 记录日志 log_entry { function: func.__name__, start_time: start_datetime, end_time: datetime.now(), elapsed_seconds: elapsed, args: args, kwargs: kwargs } print(f[性能监控] {func.__name__} 执行耗时: {elapsed:.6f} 秒) # 这里可以将log_entry保存到文件或数据库 with open(performance.log, a) as f: f.write(f{datetime.now()}: {log_entry} ) return result return wrapper def benchmark_comparison(): 对比不同实现的性能 import random performance_monitor def sum_with_for_loop(data): 使用for循环求和 total 0 for num in data: total num return total performance_monitor def sum_with_builtin(data): 使用内置sum函数求和 return sum(data) performance_monitor def sum_with_numpy(data): 使用numpy求和如果可用 try: import numpy as np return np.sum(data) except ImportError: return sum(data) # 生成测试数据 test_data [random.random() for _ in range(1000000)] print(开始性能对比测试...) # 执行测试 result1 sum_with_for_loop(test_data) result2 sum_with_builtin(test_data) result3 sum_with_numpy(test_data) print(f结果验证: {result1 result2 result3}) # 使用示例 performance_monitor def expensive_operation(n): 模拟耗时操作 total 0 for i in range(n): total i ** 2 return total # 测试单个函数 result expensive_operation(1000000) print(f计算结果: {result}) # 运行性能对比 benchmark_comparison()六、模块选择与最佳实践1. 各模块适用场景对比模块主要用途优点缺点time底层时间操作、时间戳处理、程序休眠轻量级、直接访问系统时间、精度高接口较底层、日期计算不便datetime高级日期时间处理、日期运算、格式化面向对象、易用性强、支持日期运算时区处理相对复杂calendar日历相关功能、月历/年历生成专门的日历功能、闰年判断等功能特定、使用场景有限timeit代码执行时间测量、性能测试专门用于性能测试、结果准确仅用于性能测试场景2. 最佳实践建议选择正确的模块日常日期时间处理使用datetime需要时间戳或系统级时间操作时使用time性能测试使用timeit日历相关功能使用calendar时区处理from datetime import datetime, timezone, timedelta # 创建带时区的时间 utc_time datetime.now(timezone.utc) print(fUTC时间: {utc_time}) # 时区转换 beijing_tz timezone(timedelta(hours8)) beijing_time utc_time.astimezone(beijing_tz) print(f北京时间: {beijing_time}) # 使用pytz库进行更复杂的时区处理第三方库 # import pytz # tz pytz.timezone(Asia/Shanghai)时间格式化统一# 定义统一的时间格式常量 DATETIME_FORMAT %Y-%m-%d %H:%M:%S DATE_FORMAT %Y-%m-%d TIME_FORMAT %H:%M:%S now datetime.now() print(now.strftime(DATETIME_FORMAT)) # 统一格式输出处理时间字符串解析的异常def safe_strptime(date_string, format_string): 安全解析时间字符串 try: return datetime.strptime(date_string, format_string) except ValueError as e: print(f时间字符串解析失败: {date_string} (格式: {format_string})) print(f错误信息: {e}) return None # 使用示例 valid_date safe_strptime(2024-05-12, %Y-%m-%d) invalid_date safe_strptime(2024/05/12, %Y-%m-%d) # 格式不匹配性能敏感代码使用time.perf_counter()import time # 需要高精度计时时使用perf_counter start time.perf_counter() # 执行性能敏感操作 time.sleep(0.001) end time.perf_counter() print(f耗时: {(end-start)*1000:.3f} 毫秒)掌握 Python 时间模块的核心在于理解time模块的时间戳与struct_time转换机制、熟练运用datetime模块进行日期时间计算与格式化、了解calendar模块的日历功能并在性能测试时使用timeit模块。在实际开发中datetime通常能满足大部分需求而time模块则更适合系统级或需要时间戳的场景。参考来源python时间模块_Python time时间模块用法详解pythontime模块用法_Python time时间模块用法详解python中timeit模块用法python学习7模块创建及import指令运用python标准模块 —— random随机数、time时间模块Python中的日期和时间Python生涯之常用模块学习 (一)