ITPub博客

首页 > 应用开发 > Python > 人工智能之编程进阶 Python高级:第五章 时间类模块

人工智能之编程进阶 Python高级:第五章 时间类模块

原创 Python 作者:咚咚王者 时间:2025-11-19 19:03:28 0 删除 编辑

人工智能之编程进阶 Python高级

第五章 时间类模块



前言

Python 中处理 时间与日期的核心模块有三个: time、 calendar 和 datetime。它们各有侧重,适用于不同场景。下面系统介绍它们的功能、用法、区别及最佳实践。


一、 time 模块:底层时间操作(Unix 时间戳)

基于 C 语言的 time.h,提供底层时间函数,以\ \秒为单位的时间戳(Unix Timestamp)\ \为核心。

常用函数

import time
# 1. 获取当前时间戳(浮点数,单位:秒)
ts = time.time()
print("时间戳:", ts)  # 1730987654.123456
# 2. 将时间戳转为本地时间元组(struct_time)
local = time.localtime(ts)
print("本地时间:", local)
# time.struct_time(tm_year=2025, tm_mon=11, tm_mday=7, ...)
# 3. 将时间戳转为 UTC 时间元组
utc = time.gmtime(ts)
print("UTC 时间:", utc)
# 4. 格式化时间(转为字符串)
formatted = time.strftime("%Y-%m-%d %H:%M:%S", local)
print("格式化时间:", formatted)  # 2025-11-07 18:55:00
# 5. 解析时间字符串(转为时间元组)
parsed = time.strptime("2025-11-07 18:55:00", "%Y-%m-%d %H:%M:%S")
print("解析结果:", parsed)
# 6. 睡眠(暂停程序)
time.sleep(1)  # 暂停 1 秒
# 7. 获取可读时间字符串
print(time.ctime())  # Fri Nov  7 18:55:00 2025

时间格式化代码( strftime / strptime)

| 代码     | 含义          | 示例     |

| ---------- | --------------- | ---------- |

| %Y | 四位年份      | 2025     |

| %y | 两位年份      | 25       |

| %m | 月份(01-12) | 11       |

| %d | 日(01-31)   | 07       |

| %H | 小时(00-23) | 18       |

| %M | 分钟(00-59) | 55       |

| %S | 秒(00-60)   | 30       |

| %A | 星期全名      | Friday   |

| %a | 星期缩写      | Fri      |

| %B | 月全名        | November |

| %b | 月缩写        | Nov      |

⚠️ time 模块 不处理时区转换(除本地/UTC),也不支持日期运算。


二、 calendar 模块:日历相关功能

用于生成日历、判断闰年、获取星期等。

常用功能

import calendar
# 1. 判断是否为闰年
print(calendar.isleap(2024))  # True
print(calendar.isleap(2025))  # False
# 2. 获取某月日历(文本形式)
cal_text = calendar.month(2025, 11)
print(cal_text)
#    November 2025
# Mo Tu We Th Fr Sa Su
#                1  2
#  3  4  5  6  7  8  9
# ...
# 3. 获取某月日历(列表形式)
weeks = calendar.monthcalendar(2025, 11)
print(weeks)
# [[0, 0, 0, 0, 0, 1, 2],
#  [3, 4, 5, 6, 7, 8, 9], ...]
# 4. 获取星期几(Monday=0, Sunday=6)
weekday = calendar.weekday(2025, 11, 7)  # 2025-11-07 是星期五
print("星期:", weekday)  # 4
# 5. 设置一周起始日(默认 Monday=0)
calendar.setfirstweekday(calendar.SUNDAY)
# 6. 打印全年日历
# calendar.prcal(2025)

✅ 适用场景:生成日历视图、计算工作日、节日判断等。


三、 datetime 模块:面向对象的时间处理(推荐!)

现代 Python 时间处理的首选,提供 date、 time、 datetime、 timedelta、 timezone 等类,支持 日期运算、时区、格式化等。

核心类

类 用途
datetime.date 年-月-日(无时分秒)
datetime.time 时:分:秒.微秒(无日期)
datetime.datetime 日期 + 时间(最常用)
datetime.timedelta 时间间隔(用于加减)
datetime.timezone 时区信息(UTC 或固定偏移)

1. 获取当前时间

from datetime import datetime, date, time, timedelta, timezone
# 当前本地时间(无时区信息 → naive)
now = datetime.now()
print("当前时间:", now)  # 2025-11-07 18:55:00.123456
# 当前 UTC 时间
utc_now = datetime.utcnow()  # 已弃用!推荐下面方式
utc_now = datetime.now(timezone.utc)
print("UTC 时间:", utc_now)

🔔 重要:

  • naive datetime:无时区信息(如 datetime.now())
  • aware datetime:有时区信息(如 datetime.now(timezone.utc))

避免混用 naive 和 aware 对象!


2. 创建自定义时间

# 创建具体日期时间
dt = datetime(2025, 11, 7, 18, 55, 30)
print(dt)  # 2025-11-07 18:55:30
# 仅日期
d = date(2025, 11, 7)
# 仅时间
t = time(18, 55, 30)

3. 时间格式化与解析

# 格式化为字符串
s = now.strftime("%Y-%m-%d %H:%M:%S")
print(s)  # "2025-11-07 18:55:00"
# 从字符串解析(需指定格式)
dt_parsed = datetime.strptime("2025-11-07 18:55:00", "%Y-%m-%d %H:%M:%S")
print(dt_parsed)  # datetime(2025, 11, 7, 18, 55)

💡 推荐使用第三方库 dateutil.parser.parse() 自动解析多种格式。


4. 时间运算( timedelta)

# 1 天后
tomorrow = now + timedelta(days=1)
# 2 小时 30 分钟前
past = now - timedelta(hours=2, minutes=30)
# 计算两个时间差
diff = tomorrow - now
print(diff.days)        # 1
print(diff.total_seconds())  # 86400.0
# 支持:days, seconds, microseconds, milliseconds, minutes, hours, weeks

5. 时区处理( timezone)

from datetime import timezone, timedelta
# UTC 时间
utc_dt = datetime.now(timezone.utc)
# 创建东八区(北京时间)
tz_beijing = timezone(timedelta(hours=8))
bj_dt = utc_dt.astimezone(tz_beijing)
# 或直接创建带时区的时间
bj_time = datetime(2025, 11, 7, 18, 55, tzinfo=tz_beijing)
print("UTC:", utc_dt)
print("北京:", bj_time)

🔒 生产建议: 使用 zoneinfo(Python 3.9+)或 pytz 处理复杂时区(如夏令时):

from zoneinfo import ZoneInfo
ny_time = datetime.now(ZoneInfo("America/New_York"))

6. 其他实用方法

# 获取今天日期
today = date.today()  # date(2025, 11, 7)
# 替换部分字段
new_dt = now.replace(year=2030, minute=0)
# 获取时间戳
ts = now.timestamp()  # 转为 float 时间戳
# 从时间戳创建 datetime
dt_from_ts = datetime.fromtimestamp(ts)

四、三大模块对比总结

| 功能                  | time         | calendar     | datetime         |

| ----------------------- | -------------------- | -------------------- | ------------------------ |

| 核心单位    | 秒(时间戳)       | 日历逻辑           | 日期/时间对象          |

| 面向对象    | ❌                 | ❌                 | ✅                     |

| 日期运算    | ❌                 | ❌                 | ✅ ( timedelta)   |

| 时区支持    | 仅本地/UTC         | ❌                 | ✅(需显式设置)       |

| 格式化/解析 | ✅(需格式字符串) | ❌                 | ✅(更直观)           |

| 适用场景    | 系统级、性能敏感   | 日历生成、星期计算 | 日常开发首选 |

✅ 推荐策略:

  • 新项目一律使用 datetime
  • 需要高性能时间戳用 time.time()
  • 生成日历或判断闰年用 calendar

五、典型应用场景

1. 计算年龄

from datetime import date
def calculate_age(birth_date: date) -> int:
    today = date.today()
    return today.year - birth_date.year - ((today.month, today.day) < (birth_date.month, birth_date.day))
age = calculate_age(date(1990, 5, 15))

2. 日志时间戳

from datetime import datetime
log_time = datetime.now().strftime("[%Y-%m-%d %H:%M:%S]")
print(f"{log_time} INFO: 程序启动")
# [2025-11-07 18:55:00] INFO: 程序启动

3. 定时任务间隔检查

last_run = datetime.now()
interval = timedelta(minutes=5)
if datetime.now() - last_run > interval:
    print("执行任务...")
    last_run = datetime.now()

4. 时区转换(Web 应用)

from datetime import datetime, timezone
from zoneinfo import ZoneInfo  # Python 3.9+
user_tz = ZoneInfo("Asia/Shanghai")
utc_time = datetime.now(timezone.utc)
local_time = utc_time.astimezone(user_tz)

六、注意事项与最佳实践

  1. 始终明确时区:
  • 存储时间用 UTC
  • 展示给用户时转为本地时区
  1. 避免 naive datetime:
  • 在涉及多时区系统中,务必使用 aware datetime
  1. 不要用 datetime.utcnow():
  • 它返回的是 naive 对象,应改用 datetime.now(timezone.utc)
  1. 时间比较前确保类型一致:
  • naive 不能与 aware 比较,会报错
  1. 解析用户输入时验证格式:
  • 使用 try-except 捕获 ValueError

七、扩展建议

  • 复杂时区:使用 zoneinfo(Python 3.9+ 内置)或 pytz
  • 自然语言解析: dateutil.parser
  • 高性能时间处理: pandas.Timestamp(大数据场景)

总结

经过学习常见的时间模块 time、 calendar 和 datetime,我们可以有效解决 Python 中所有时间与日期相关的需求!建议 优先使用 datetime,它是现代 Python 时间处理的标准答案。

资料关注

公众号:咚咚王

《Python编程:从入门到实践》 《利用Python进行数据分析》 《算法导论中文第三版》 《概率论与数理统计(第四版) (盛骤) 》 《程序员的数学》 《线性代数应该这样学第3版》 《微积分和数学分析引论》 《(西瓜书)周志华-机器学习》 《TensorFlow机器学习实战指南》 《Sklearn与TensorFlow机器学习实用指南》 《模式识别(第四版)》 《深度学习 deep learning》伊恩·古德费洛著 花书 《Python深度学习第二版(中文版)【纯文本】 (登封大数据 (Francois Choliet)) (Z-Library)》 《深入浅出神经网络与深度学习+(迈克尔·尼尔森(Michael+Nielsen) 》 《自然语言处理综论  第2版》 《Natural-Language-Processing-with-PyTorch》 《计算机视觉-算法与应用(中文版)》 《Learning OpenCV 4》 《AIGC:智能创作时代》杜雨+&+张孜铭 《AIGC原理与实践:零基础学大语言模型、扩散模型和多模态模型》 《从零构建大语言模型(中文版)》 《实战AI大模型》 《AI 3.0》

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70048224/viewspace-3102496/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
深耕人工智能领域,做你的随身笔记。

注册时间:2025-10-26

  • 博文量
    47
  • 访问量
    46031