Python模块:内置模块datetime日期时间处理详解
一、开篇:日期时间——编程中最容易出错的领域之一
日期时间处理看似简单,实则充满陷阱:时区转换、闰年判断、夏令时跳变、字符串格式化和解析……Python的datetime模块提供了处理这一切的工具。
⌨️ 先认识四个核心类:
fromdatetimeimportdate,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 创建和基本属性
fromdatetimeimportdate# 创建日期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 日期比较和计算
fromdatetimeimportdate,timedeltafromdatetimeimportdateasDate# 日期比较d1=Date(2024,1,1)d2=Date(2024,12,31)print(d1<d2)# Trueprint(d1==d2)# Falseprint(d1!=d2)# True# 日期差——返回timedeltadelta=d2-d1print(f"相差天数:{delta.days}")# 365# 日期加减timedeltanext_week=Date.today()+timedelta(weeks=1)yesterday=Date.today()-timedelta(days=1)print(f"下周今天:{next_week}")print(f"昨天:{yesterday}")# 计算年龄defcalculate_age(birth_date):"""计算年龄"""today=Date.today()age=today.year-birth_date.year# 如果今年的生日还没过,减1岁iftoday.month<birth_date.monthor\(today.month==birth_date.monthandtoday.day<birth_date.day):age-=1returnage birth=Date(1995,8,20)print(f"出生日期:{birth}, 年龄:{calculate_age(birth)}")三、datetime类——日期时间完整操作
3.1 创建和获取当前时间
fromdatetimeimportdatetime# 创建datetimedt1=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和timefromdatetimeimportdate,time d=date(2024,6,15)t=time(14,30,0)dt=datetime.combine(d,t)print(f"组合:{dt}")# 从时间戳创建ts=1718000000.0dt_from_ts=datetime.fromtimestamp(ts)print(f"时间戳{ts}→{dt_from_ts}")3.2 时间差计算
fromdatetimeimportdatetime,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-startprint(f"相差:{diff.days}天,{diff.seconds}秒")print(f"总共:{diff.total_seconds():.0f}秒")print(f"约:{diff.total_seconds()/3600:.0f}小时")# 实战:计算倒计时defcountdown(target_date):"""计算距离目标日期还有多久"""now=datetime.now()remaining=target_date-nowifremaining.total_seconds()<0:return"已过期"days=remaining.days hours,remainder=divmod(remaining.seconds,3600)minutes=remainder//60returnf"{days}天{hours}小时{minutes}分钟"target=datetime(2025,1,1,0,0,0)print(f"距离新年还有:{countdown(target)}")四、字符串格式化
4.1 strftime()——格式化输出
fromdatetimeimportdatetime 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-15print(now.strftime("%Y年%m月%d日"))# 2024年06月15日print(now.strftime("%Y-%m-%d %H:%M:%S"))# 2024-06-15 14:30:00print(now.strftime("%A, %B %d, %Y"))# Saturday, June 15, 2024print(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()——解析字符串
fromdatetimeimportdatetime# strptime() —— 字符串转datetime# 最常出错的环节——格式必须精确匹配date_str1="2024-06-15"dt1=datetime.strptime(date_str1,"%Y-%m-%d")print(dt1)# 2024-06-15 00:00:00date_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:00date_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!# 处理多种日期格式defparse_date(date_string):"""尝试多种格式解析日期"""formats=["%Y-%m-%d","%Y/%m/%d","%Y年%m月%d日","%d-%m-%Y","%m/%d/%Y",]forfmtinformats:try:returndatetime.strptime(date_string,fmt)exceptValueError:continueraiseValueError(f"无法解析日期:{date_string}")print(parse_date("2024-06-15"))print(parse_date("06/15/2024"))五、时区处理
fromdatetimeimportdatetime,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+8dt_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()解析。格式代码要精确匹配。