Python模块:内置模块datetime日期时间处理详解

一、开篇:日期时间——编程中最容易出错的领域之一
日期时间处理看似简单,实则充满陷阱:时区转换、闰年判断、夏令时跳变、字符串格式化和解析……Python的datetime模块提供了处理这一切的工具。
⌨️ 先认识四个核心类:
from datetime import date, time, datetime, timedelta
# date —— 日期(年、月、日)
d = date(2024, 6, 15)
# time —— 时间(时、分、秒、微秒)
t = time(14, 30, 0)
# datetime —— 日期+时间
dt = datetime(2024, 6, 15, 14, 30, 0)
# timedelta —— 时间差(天数、秒数等)
delta = timedelta(days=7)
# 💡 这四个类覆盖了90%的日期时间操作需求
二、date类——日期操作
2.1 创建和基本属性
from datetime import date
# 创建日期
d1 = date(2024, 6, 15) # 指定年月日
d2 = date.today() # 今天
d3 = date.fromisoformat("2024-06-15") # 从ISO格式字符串
print(f"今天: {d2}")
print(f"年: {d2.year}, 月: {d2.month}, 日: {d2.day}")
# 星期几:weekday() 0=周一~6=周日, isoweekday() 1=周一~7=周日
print(f"星期几(weekday): {d2.weekday()}") # 0=周一
print(f"星期几(isoweekday): {d2.isoweekday()}") # 1=周一
# 替换字段——返回新对象
next_year = d2.replace(year=d2.year + 1)
print(f"明年今日: {next_year}")
# ISO日历信息
print(f"ISO年份: {d2.isocalendar().year}")
print(f"ISO周数: {d2.isocalendar().week}")
2.2 日期比较和计算
from datetime import date, timedelta
from datetime import date as Date
# 日期比较
d1 = Date(2024, 1, 1)
d2 = Date(2024, 12, 31)
print(d1 < d2) # True
print(d1 == d2) # False
print(d1 != d2) # True
# 日期差——返回timedelta
delta = d2 - d1
print(f"相差天数: {delta.days}") # 365
# 日期加减timedelta
next_week = Date.today() + timedelta(weeks=1)
yesterday = Date.today() - timedelta(days=1)
print(f"下周今天: {next_week}")
print(f"昨天: {yesterday}")
# 计算年龄
def calculate_age(birth_date):
"""计算年龄"""
today = Date.today()
age = today.year - birth_date.year
# 如果今年的生日还没过,减1岁
if today.month < birth_date.month or \
(today.month == birth_date.month and today.day < birth_date.day):
age -= 1
return age
birth = Date(1995, 8, 20)
print(f"出生日期: {birth}, 年龄: {calculate_age(birth)}")
三、datetime类——日期时间完整操作
3.1 创建和获取当前时间
from datetime import datetime
# 创建datetime
dt1 = datetime(2024, 6, 15, 14, 30, 0)
dt2 = datetime(2024, 6, 15, 14, 30, 0, 500000) # 带微秒
# 获取当前时间
now = datetime.now() # 本地当前时间
utc_now = datetime.utcnow() # UTC当前时间(带警告,推荐用时区)
print(f"当前时间: {now}")
print(f"时间戳: {now.timestamp()}") # Unix时间戳
# datetime属性
print(f"年={now.year}, 月={now.month}, 日={now.day}")
print(f"时={now.hour}, 分={now.minute}, 秒={now.second}")
print(f"微秒={now.microsecond}")
# 组合date和time
from datetime import date, time
d = date(2024, 6, 15)
t = time(14, 30, 0)
dt = datetime.combine(d, t)
print(f"组合: {dt}")
# 从时间戳创建
ts = 1718000000.0
dt_from_ts = datetime.fromtimestamp(ts)
print(f"时间戳{ts} → {dt_from_ts}")
3.2 时间差计算
from datetime import datetime, timedelta
now = datetime.now()
# timedelta创建
one_day = timedelta(days=1)
one_week = timedelta(weeks=1)
three_hours = timedelta(hours=3)
complex_delta = timedelta(days=2, hours=5, minutes=30)
# 日期时间运算
tomorrow = now + one_day
last_week = now - one_week
future_dt = now + timedelta(days=30, hours=12)
print(f"明天: {tomorrow}")
print(f"30天12小时后: {future_dt}")
# 两个datetime之差
start = datetime(2024, 1, 1, 9, 0)
end = datetime(2024, 6, 15, 18, 30)
diff = end - start
print(f"相差: {diff.days}天, {diff.seconds}秒")
print(f"总共: {diff.total_seconds():.0f}秒")
print(f"约: {diff.total_seconds() / 3600:.0f}小时")
# 实战:计算倒计时
def countdown(target_date):
"""计算距离目标日期还有多久"""
now = datetime.now()
remaining = target_date - now
if remaining.total_seconds() < 0:
return "已过期"
days = remaining.days
hours, remainder = divmod(remaining.seconds, 3600)
minutes = remainder // 60
return f"{days}天{hours}小时{minutes}分钟"
target = datetime(2025, 1, 1, 0, 0, 0)
print(f"距离新年还有: {countdown(target)}")
四、字符串格式化
4.1 strftime()——格式化输出
from datetime import datetime
now = datetime.now()
# strftime() —— datetime转字符串
# 常用格式代码:
# %Y: 4位年份 %m: 月份(01-12) %d: 日(01-31)
# %H: 24小时制 %I: 12小时制 %M: 分钟
# %S: 秒 %f: 微秒 %p: AM/PM
# %A: 完整星期名 %B: 完整月份名
# %w: 星期(0=周日) %j: 年内第几天
print(now.strftime("%Y-%m-%d")) # 2024-06-15
print(now.strftime("%Y年%m月%d日")) # 2024年06月15日
print(now.strftime("%Y-%m-%d %H:%M:%S")) # 2024-06-15 14:30:00
print(now.strftime("%A, %B %d, %Y")) # Saturday, June 15, 2024
print(now.strftime("%Y-%m-%d %H:%M:%S.%f")[:23]) # 带微秒
# 中文日期格式
weekdays_cn = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
print(f"中文: {now.year}年{now.month}月{now.day}日 "
f"{weekdays_cn[now.weekday()]}")
4.2 strptime()——解析字符串
from datetime import datetime
# strptime() —— 字符串转datetime
# 最常出错的环节——格式必须精确匹配
date_str1 = "2024-06-15"
dt1 = datetime.strptime(date_str1, "%Y-%m-%d")
print(dt1) # 2024-06-15 00:00:00
date_str2 = "2024年06月15日 14:30:00"
dt2 = datetime.strptime(date_str2, "%Y年%m月%d日 %H:%M:%S")
print(dt2) # 2024-06-15 14:30:00
date_str3 = "15/06/2024"
dt3 = datetime.strptime(date_str3, "%d/%m/%Y")
print(dt3) # 2024-06-15 00:00:00
# ⚠️ 常见错误:格式不匹配
# datetime.strptime("2024-06-15", "%Y/%m/%d") # ValueError!
# 处理多种日期格式
def parse_date(date_string):
"""尝试多种格式解析日期"""
formats = [
"%Y-%m-%d",
"%Y/%m/%d",
"%Y年%m月%d日",
"%d-%m-%Y",
"%m/%d/%Y",
]
for fmt in formats:
try:
return datetime.strptime(date_string, fmt)
except ValueError:
continue
raise ValueError(f"无法解析日期: {date_string}")
print(parse_date("2024-06-15"))
print(parse_date("06/15/2024"))
五、时区处理
from datetime import datetime, timezone, timedelta
# Python 3.9+推荐的方式
# UTC时区
utc_tz = timezone.utc
# 创建带时区的时间
dt_utc = datetime(2024, 6, 15, 14, 30, tzinfo=utc_tz)
print(f"UTC时间: {dt_utc}")
# 创建特定时区(固定偏移)
cst = timezone(timedelta(hours=8)) # 中国标准时间 UTC+8
dt_cst = datetime(2024, 6, 15, 14, 30, tzinfo=cst)
print(f"北京时间: {dt_cst}")
# 时区转换
dt_utc = datetime.now(timezone.utc)
dt_beijing = dt_utc.astimezone(timezone(timedelta(hours=8)))
print(f"UTC: {dt_utc}")
print(f"北京: {dt_beijing}")
# 💡 更完整的时区支持需要第三方库:
# pip install pytz # 经典方案
# pip install zoneinfo # Python 3.9+内置(推荐)
六、总结
datetime模块是处理日期时间的瑞士军刀。掌握它的四个核心类和格式化操作,就能应对绝大多数日期时间需求。
💡 核心要点:
| 类 | 用途 | 关键方法 |
|---|---|---|
date | 日期 | today(), weekday(), replace() |
time | 时间 | replace() |
datetime | 日期+时间 | now(), strftime(), strptime(), timestamp() |
timedelta | 时间差 | days, seconds, total_seconds() |
✅ 字符串格式化是重点:strftime()输出,strptime()解析。格式代码要精确匹配。

8万+

被折叠的 条评论
为什么被折叠?



