Python模块内置模块datetime日期时间处理详解一、开篇日期时间——编程中最容易出错的领域之一日期时间处理看似简单实则充满陷阱时区转换、闰年判断、夏令时跳变、字符串格式化和解析……Python的datetime模块提供了处理这一切的工具。⌨️ 先认识四个核心类fromdatetimeimportdate,time,datetime,timedelta# date —— 日期年、月、日ddate(2024,6,15)# time —— 时间时、分、秒、微秒ttime(14,30,0)# datetime —— 日期时间dtdatetime(2024,6,15,14,30,0)# timedelta —— 时间差天数、秒数等deltatimedelta(days7)# 这四个类覆盖了90%的日期时间操作需求二、date类——日期操作2.1 创建和基本属性fromdatetimeimportdate# 创建日期d1date(2024,6,15)# 指定年月日d2date.today()# 今天d3date.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_yeard2.replace(yeard2.year1)print(f明年今日:{next_year})# ISO日历信息print(fISO年份:{d2.isocalendar().year})print(fISO周数:{d2.isocalendar().week})2.2 日期比较和计算fromdatetimeimportdate,timedeltafromdatetimeimportdateasDate# 日期比较d1Date(2024,1,1)d2Date(2024,12,31)print(d1d2)# Trueprint(d1d2)# Falseprint(d1!d2)# True# 日期差——返回timedeltadeltad2-d1print(f相差天数:{delta.days})# 365# 日期加减timedeltanext_weekDate.today()timedelta(weeks1)yesterdayDate.today()-timedelta(days1)print(f下周今天:{next_week})print(f昨天:{yesterday})# 计算年龄defcalculate_age(birth_date):计算年龄todayDate.today()agetoday.year-birth_date.year# 如果今年的生日还没过减1岁iftoday.monthbirth_date.monthor\(today.monthbirth_date.monthandtoday.daybirth_date.day):age-1returnage birthDate(1995,8,20)print(f出生日期:{birth}, 年龄:{calculate_age(birth)})三、datetime类——日期时间完整操作3.1 创建和获取当前时间fromdatetimeimportdatetime# 创建datetimedt1datetime(2024,6,15,14,30,0)dt2datetime(2024,6,15,14,30,0,500000)# 带微秒# 获取当前时间nowdatetime.now()# 本地当前时间utc_nowdatetime.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 ddate(2024,6,15)ttime(14,30,0)dtdatetime.combine(d,t)print(f组合:{dt})# 从时间戳创建ts1718000000.0dt_from_tsdatetime.fromtimestamp(ts)print(f时间戳{ts}→{dt_from_ts})3.2 时间差计算fromdatetimeimportdatetime,timedelta nowdatetime.now()# timedelta创建one_daytimedelta(days1)one_weektimedelta(weeks1)three_hourstimedelta(hours3)complex_deltatimedelta(days2,hours5,minutes30)# 日期时间运算tomorrownowone_day last_weeknow-one_week future_dtnowtimedelta(days30,hours12)print(f明天:{tomorrow})print(f30天12小时后:{future_dt})# 两个datetime之差startdatetime(2024,1,1,9,0)enddatetime(2024,6,15,18,30)diffend-startprint(f相差:{diff.days}天,{diff.seconds}秒)print(f总共:{diff.total_seconds():.0f}秒)print(f约:{diff.total_seconds()/3600:.0f}小时)# 实战计算倒计时defcountdown(target_date):计算距离目标日期还有多久nowdatetime.now()remainingtarget_date-nowifremaining.total_seconds()0:return已过期daysremaining.days hours,remainderdivmod(remaining.seconds,3600)minutesremainder//60returnf{days}天{hours}小时{minutes}分钟targetdatetime(2025,1,1,0,0,0)print(f距离新年还有:{countdown(target)})四、字符串格式化4.1 strftime()——格式化输出fromdatetimeimportdatetime nowdatetime.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_str12024-06-15dt1datetime.strptime(date_str1,%Y-%m-%d)print(dt1)# 2024-06-15 00:00:00date_str22024年06月15日 14:30:00dt2datetime.strptime(date_str2,%Y年%m月%d日 %H:%M:%S)print(dt2)# 2024-06-15 14:30:00date_str315/06/2024dt3datetime.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_tztimezone.utc# 创建带时区的时间dt_utcdatetime(2024,6,15,14,30,tzinfoutc_tz)print(fUTC时间:{dt_utc})# 创建特定时区固定偏移csttimezone(timedelta(hours8))# 中国标准时间 UTC8dt_cstdatetime(2024,6,15,14,30,tzinfocst)print(f北京时间:{dt_cst})# 时区转换dt_utcdatetime.now(timezone.utc)dt_beijingdt_utc.astimezone(timezone(timedelta(hours8)))print(fUTC:{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()解析。格式代码要精确匹配。