Python datetime 教程
Python 的 datetime
模块提供了处理日期和时间的类,主要包含以下类:
date
- 处理日期(年、月、日)time
- 处理时间(时、分、秒、微秒)datetime
- 处理日期和时间timedelta
- 处理时间间隔tzinfo
- 处理时区信息
创建日期时间对象
# 当前日期和时间
now = datetime.now()
print(f"当前时间: {now}")# 特定日期
specific_date = date(2023, 12, 25)
print(f"特定日期: {specific_date}")# 特定时间
specific_time = time(14, 30, 45)
print(f"特定时间: {specific_time}")# 特定日期时间
specific_datetime = datetime(2023, 12, 25, 14, 30, 45)
print(f"特定日期时间: {specific_datetime}")
获取各个组件
now = datetime.now()print(f"年: {now.year}")
print(f"月: {now.month}")
print(f"日: {now.day}")
print(f"时: {now.hour}")
print(f"分: {now.minute}")
print(f"秒: {now.second}")
print(f"微秒: {now.microsecond}")
print(f"星期几: {now.weekday()}") # 0=周一, 6=周日
print(f"ISO 星期几: {now.isoweekday()}") # 1=周一, 7=周日
日期计算
from datetime import date, timedeltatoday = date.today()
print(f"今天: {today}")# 明天
tomorrow = today + timedelta(days=1)
print(f"明天: {tomorrow}")# 昨天
yesterday = today - timedelta(days=1)
print(f"昨天: {yesterday}")# 一周后
next_week = today + timedelta(weeks=1)
print(f"一周后: {next_week}")
日期比较
date1 = date(2023, 1, 1)
date2 = date(2023, 12, 31)print(f"date1 < date2: {date1 < date2}")
print(f"date1 == date2: {date1 == date2}")
print(f"date1 > date2: {date1 > date2}")
时间计算
from datetime import time, timedeltacurrent_time = datetime.now().time()
print(f"当前时间: {current_time}")# 创建时间对象
lunch_time = time(12, 0, 0)
meeting_time = time(14, 30, 0)print(f"午餐时间: {lunch_time}")
print(f"会议时间: {meeting_time}")
日期时间转字符串
now = datetime.now()# 常用格式
print(now.strftime("%Y-%m-%d")) # 2023-12-25
print(now.strftime("%d/%m/%Y")) # 25/12/2023
print(now.strftime("%A, %B %d, %Y")) # Monday, December 25, 2023
print(now.strftime("%H:%M:%S")) # 14:30:45
print(now.strftime("%I:%M %p")) # 02:30 PM# ISO 格式
print(now.isoformat()) # 2023-12-25T14:30:45.123456
字符串转日期时间
# 从字符串解析
date_str = "2023-12-25"
parsed_date = datetime.strptime(date_str, "%Y-%m-%d")
print(f"解析的日期: {parsed_date}")datetime_str = "2023-12-25 14:30:45"
parsed_datetime = datetime.strptime(datetime_str, "%Y-%m-%d %H:%M:%S")
print(f"解析的日期时间: {parsed_datetime}")
常用格式代码
代码 | 含义 | 示例 |
---|---|---|
%Y | 4位数年份 | 2023 |
%m | 2位数月份 | 12 |
%d | 2位数日期 | 25 |
%H | 24小时制小时 | 14 |
%I | 12小时制小时 | 02 |
%M | 分钟 | 30 |
%S | 秒 | 45 |
%p | AM/PM | PM |
%A | 完整星期名 | Monday |
%B | 完整月份名 | December |
基本时区操作
from datetime import datetime, timezone, timedelta# UTC 时间
utc_now = datetime.now(timezone.utc)
print(f"UTC 时间: {utc_now}")# 创建特定时区
# 东八区(北京时间)
beijing_tz = timezone(timedelta(hours=8))
beijing_time = datetime.now(beijing_tz)
print(f"北京时间: {beijing_time}")# 时区转换
utc_time = datetime(2023, 12, 25, 12, 0, 0, tzinfo=timezone.utc)
beijing_time = utc_time.astimezone(timezone(timedelta(hours=8)))
print(f"UTC 时间: {utc_time}")
print(f"转换后的北京时间: {beijing_time}")
使用 pytz 库(第三方)
# 首先安装: pip install pytz
import pytz# 获取时区
utc = pytz.UTC
beijing_tz = pytz.timezone('Asia/Shanghai')
new_york_tz = pytz.timezone('America/New_York')# 时区感知的 datetime
dt_utc = datetime.now(utc)
dt_beijing = datetime.now(beijing_tz)
dt_ny = dt_beijing.astimezone(new_york_tz)print(f"UTC: {dt_utc}")
print(f"北京时间: {dt_beijing}")
print(f"纽约时间: {dt_ny}")
timedelta 使用
from datetime import datetime, timedelta# 创建时间差
delta1 = timedelta(days=7)
delta2 = timedelta(hours=5, minutes=30)print(f"一周的时间差: {delta1}")
print(f"5小时30分钟的时间差: {delta2}")# 日期时间计算
start_time = datetime(2023, 1, 1, 9, 0, 0)
end_time = start_time + timedelta(hours=8, days=1)print(f"开始时间: {start_time}")
print(f"结束时间: {end_time}")# 计算两个时间的差值
time_diff = end_time - start_time
print(f"时间差: {time_diff}")
print(f"总秒数: {time_diff.total_seconds()}")
案列:
示例1:计算年龄
def calculate_age(birth_date):today = date.today()age = today.year - birth_date.year# 检查生日是否已过if today < date(today.year, birth_date.month, birth_date.day):age -= 1return agebirthday = date(1990, 6, 15)
age = calculate_age(birthday)
print(f"年龄: {age} 岁")
示例2:工作日计算
def add_workdays(start_date, days_to_add):current_date = start_dateworkdays_added = 0while workdays_added < days_to_add:current_date += timedelta(days=1)# 周一至周五为工作日if current_date.weekday() < 5:workdays_added += 1return current_datestart_date = date(2023, 12, 25) # 周一
result_date = add_workdays(start_date, 3)
print(f"开始日期: {start_date}")
print(f"3个工作日后: {result_date}")
示例3:倒计时应用
def countdown(target_date, target_name):today = datetime.now().date()days_remaining = (target_date - today).daysif days_remaining > 0:return f"距离{target_name}还有 {days_remaining} 天"elif days_remaining == 0:return f"{target_name}就是今天!"else:return f"{target_name}已经过去 {abs(days_remaining)} 天"new_year = date(2024, 1, 1)
print(countdown(new_year, "元旦"))
示例3:日志时间戳
def log_message(message):timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")print(f"[{timestamp}] {message}")log_message("系统启动")
log_message("用户登录")
示例4:时间段分割
def split_time_range(start, end, interval_minutes):current = startintervals = []while current < end:next_time = current + timedelta(minutes=interval_minutes)if next_time > end:next_time = endintervals.append((current, next_time))current = next_timereturn intervalsstart_time = datetime(2023, 12, 25, 9, 0, 0)
end_time = datetime(2023, 12, 25, 17, 0, 0)
time_slots = split_time_range(start_time, end_time, 30)for i, (slot_start, slot_end) in enumerate(time_slots):print(f"时间段 {i+1}: {slot_start.strftime('%H:%M')} - {slot_end.strftime('%H:%M')}")
总结
Python 的 datetime
模块提供了强大而灵活的日期时间处理功能。通过掌握本教程的内容,您将能够:
创建和操作日期时间对象
格式化日期时间字符串
处理时区转换
计算时间差
解决实际应用中的日期时间问题