
第五章 时间类模块
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 2025strftime / strptime)代码 | 含义 | 示例 |
|---|---|---|
| 四位年份 | 2025 |
| 两位年份 | 25 |
| 月份(01-12) | 11 |
| 日(01-31) | 07 |
| 小时(00-23) | 18 |
| 分钟(00-59) | 55 |
| 秒(00-60) | 30 |
| 星期全名 | Friday |
| 星期缩写 | Fri |
| 月全名 | November |
| 月缩写 | 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 等类,支持日期运算、时区、格式化等。
类 | 用途 |
|---|---|
| 年-月-日(无时分秒) |
| 时:分:秒.微秒(无日期) |
| 日期 + 时间(最常用) |
| 时间间隔(用于加减) |
| 时区信息(UTC 或固定偏移) |
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 对象!
# 创建具体日期时间
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)# 格式化为字符串
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()自动解析多种格式。
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, weekstimezone)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"))
# 获取今天日期
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)功能 |
|
|
|
|---|---|---|---|
核心单位 | 秒(时间戳) | 日历逻辑 | 日期/时间对象 |
面向对象 | ❌ | ❌ | ✅ |
日期运算 | ❌ | ❌ | ✅ ( |
时区支持 | 仅本地/UTC | ❌ | ✅(需显式设置) |
格式化/解析 | ✅(需格式字符串) | ❌ | ✅(更直观) |
适用场景 | 系统级、性能敏感 | 日历生成、星期计算 | 日常开发首选 |
✅ 推荐策略:新项目一律使用
datetime需要高性能时间戳用time.time()生成日历或判断闰年用calendar
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))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: 程序启动last_run = datetime.now()
interval = timedelta(minutes=5)
if datetime.now() - last_run > interval:
print("执行任务...")
last_run = datetime.now()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)datetime.utcnow():datetime.now(timezone.utc)try-except 捕获 ValueErrorzoneinfo(Python 3.9+ 内置)或 pytzdateutil.parserpandas.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》
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。