怎样通过Python案例掌握时间日期模块的使用

访客 python案例 1

本文目录导读:

  1. 案例1:基础时间操作 - 个人日程提醒器
  2. 案例2:时间格式化与解析 - 日志分析工具
  3. 案例3:时区处理 - 全球会议时间转换器
  4. 案例4:时间计算与统计 - 项目计时器
  5. 案例5:日期运算 - 生日倒计时与纪念日计算
  6. 关键知识点总结

我来通过几个实用的Python案例,帮助你掌握时间日期模块(datetime)的使用。

案例1:基础时间操作 - 个人日程提醒器

from datetime import datetime, date, time, timedelta
import time as time_module
class ScheduleReminder:
    """个人日程提醒器"""
    def __init__(self):
        self.events = []
    def add_event(self, name, event_date, event_time):
        """添加日程事件"""
        # 组合日期和时间
        event_datetime = datetime.combine(event_date, event_time)
        self.events.append({
            'name': name,
            'datetime': event_datetime
        })
        print(f"✅ 已添加事件: {name} 于 {event_datetime}")
    def check_upcoming_events(self, hours_ahead=24):
        """检查未来几小时的事件"""
        now = datetime.now()
        deadline = now + timedelta(hours=hours_ahead)
        print(f"\n📋 hours_ahead}小时内的日程:")
        upcoming = []
        for event in self.events:
            if now <= event['datetime'] <= deadline:
                time_left = event['datetime'] - now
                hours = time_left.total_seconds() // 3600
                minutes = (time_left.total_seconds() % 3600) // 60
                print(f"  📌 {event['name']} - 还有{int(hours)}小时{int(minutes)}分钟")
                upcoming.append(event)
        if not upcoming:
            print("  🎉 暂无即将到来的事件")
        return upcoming
# 使用示例
reminder = ScheduleReminder()
# 添加一些日程
today = date.today()
reminder.add_event("项目会议", today, time(14, 30))
reminder.add_event("健身时间", today, time(18, 0))
# 明天的事件
tomorrow = today + timedelta(days=1)
reminder.add_event("周报提交", tomorrow, time(9, 0))
# 检查未来24小时的事件
reminder.check_upcoming_events(24)

案例2:时间格式化与解析 - 日志分析工具

from datetime import datetime
import re
from collections import Counter
class LogAnalyzer:
    """日志时间分析工具"""
    def __init__(self):
        # 常见的时间格式
        self.formats = {
            'ISO': '%Y-%m-%d %H:%M:%S',
            'US': '%m/%d/%Y %I:%M %p',
            'EURO': '%d/%m/%Y %H:%M',
            'LOG': '%b %d %H:%M:%S'
        }
    def parse_time(self, time_string, format_name=None):
        """解析时间字符串"""
        if format_name:
            try:
                return datetime.strptime(time_string, self.formats[format_name])
            except (ValueError, KeyError) as e:
                print(f"❌ 解析失败: {e}")
                return None
        # 自动尝试所有格式
        for name, fmt in self.formats.items():
            try:
                result = datetime.strptime(time_string, fmt)
                print(f"✓ 使用{name}格式解析成功")
                return result
            except ValueError:
                continue
        print(f"❌ 无法解析: {time_string}")
        return None
    def format_time(self, dt, format_name='ISO'):
        """格式化时间输出"""
        if format_name in self.formats:
            return dt.strftime(self.formats[format_name])
        return dt.isoformat()
    def analyze_log_times(self, log_text):
        """分析日志中的时间分布"""
        # 提取所有时间戳(假设格式为 YYYY-MM-DD HH:MM:SS)
        time_pattern = r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}'
        timestamps = re.findall(time_pattern, log_text)
        if not timestamps:
            print("❌ 未找到时间戳")
            return
        # 解析时间并分析小时分布
        hours = []
        for ts in timestamps:
            dt = datetime.strptime(ts, '%Y-%m-%d %H:%M:%S')
            hours.append(dt.hour)
        hour_distribution = Counter(hours)
        print(f"\n📊 时间分析报告(共{len(timestamps)}个记录)")
        print("-" * 40)
        for hour in sorted(hour_distribution.keys()):
            count = hour_distribution[hour]
            bar = '█' * count
            print(f"{hour:02d}:00 {bar} ({count}次)")
# 使用示例
analyzer = LogAnalyzer()
# 时间解析示例
print("=== 时间解析测试 ===")
test_times = [
    "2024-04-05 14:30:00",
    "04/05/2024 02:30 PM",
    "05/04/2024 14:30",
    "Apr 05 14:30:00"
]
for time_str in test_times:
    result = analyzer.parse_time(time_str)
    if result:
        print(f"  解析结果: {result}")
        print(f"  格式化输出: {analyzer.format_time(result, 'US')}")
    print()
# 日志分析示例
sample_log = """
2024-04-05 08:15:23 [INFO] 系统启动
2024-04-05 08:30:45 [INFO] 用户登录
2024-04-05 09:00:12 [ERROR] 数据库连接失败
2024-04-05 10:45:33 [INFO] 任务完成
2024-04-05 14:20:18 [WARN] 内存使用过高
2024-04-05 14:25:00 [INFO] 备份完成
2024-04-05 15:30:22 [INFO] 用户登出
"""
analyzer.analyze_log_times(sample_log)

案例3:时区处理 - 全球会议时间转换器

from datetime import datetime, timezone, timedelta
from dateutil import tz
from functools import lru_cache
class TimeZoneConverter:
    """时区转换工具"""
    def __init__(self):
        self.timezones = {
            '北京': 'Asia/Shanghai',
            '东京': 'Asia/Tokyo',
            '纽约': 'America/New_York',
            '伦敦': 'Europe/London',
            '巴黎': 'Europe/Paris',
            '悉尼': 'Australia/Sydney',
            '迪拜': 'Asia/Dubai'
        }
    def get_current_time(self, city_name):
        """获取指定城市的当前时间"""
        if city_name not in self.timezones:
            print(f"❌ 未知城市: {city_name}")
            return None
        timezone_name = self.timezones[city_name]
        try:
            tz_info = tz.gettz(timezone_name)
            current_time = datetime.now(tz_info)
            return current_time
        except Exception as e:
            print(f"❌ 错误: {e}")
            return None
    def convert_time(self, dt, from_city, to_city):
        """在不同城市间转换时间"""
        if from_city not in self.timezones or to_city not in self.timezones:
            print("❌ 未知城市")
            return None
        try:
            # 将原始时间设为源时区
            from_tz = tz.gettz(self.timezones[from_city])
            to_tz = tz.gettz(self.timezones[to_city])
            # 确保datetime有时区信息
            if dt.tzinfo is None:
                dt = dt.replace(tzinfo=from_tz)
            else:
                dt = dt.astimezone(from_tz)
            # 转换到目标时区
            converted = dt.astimezone(to_tz)
            return converted
        except Exception as e:
            print(f"❌ 转换失败: {e}")
            return None
    def find_best_meeting_time(self, participants, duration_hours=1):
        """找到最佳会议时间(假设在9:00-17:00之间)"""
        print(f"\n🌍 寻找{len(participants)}个城市的会议时间")
        # 假设在各自的时区时间的9:00-17:00为工作时间
        best_times = []
        for hour in range(9, 16):  # 尝试每个整点
            feasible = True
            times = {}
            for city in participants:
                # 假设会议在北京时间hour:00开始
                base_time = datetime.now().replace(
                    hour=hour, minute=0, second=0, microsecond=0
                )
                local_time = self.convert_time(base_time, '北京', city)
                if local_time:
                    times[city] = local_time
                    # 检查是否在工作时间(9:00-17:00)
                    if local_time.hour < 9 or local_time.hour >= 17:
                        feasible = False
                        break
            if feasible:
                best_times.append(times)
        return best_times
# 使用示例
converter = TimeZoneConverter()
# 显示主要城市当前时间
print("=== 全球主要城市当前时间 ===")
cities = ['北京', '纽约', '伦敦', '东京', '悉尼']
for city in cities:
    current_time = converter.get_current_time(city)
    if current_time:
        print(f"{city}: {current_time.strftime('%Y-%m-%d %H:%M:%S')}")
# 时间转换示例
print("\n=== 时间转换 ===")
beijing_time = datetime(2024, 4, 5, 14, 30)  # 北京时间14:30
nyc_time = converter.convert_time(beijing_time, '北京', '纽约')
if nyc_time:
    print(f"北京时间 {beijing_time} 对应纽约时间为: {nyc_time}")
# 查找最佳会议时间
print("\n=== 寻找最佳会议时间 ===")
participants = ['北京', '纽约', '伦敦']
best_times = converter.find_best_meeting_time(participants)
if best_times:
    print(f"找到{len(best_times)}个可行时间:")
    for time_slot in best_times[:3]:  # 显示前3个
        for city, dt in time_slot.items():
            print(f"  {city}: {dt.strftime('%H:%M')}")
        print()
else:
    print("❌ 未找到合适的时间")

案例4:时间计算与统计 - 项目计时器

from datetime import datetime, timedelta
import time as time_module
class ProjectTimer:
    """项目计时器"""
    def __init__(self):
        self.tasks = {}
        self.current_task = None
        self.start_time = None
    def start_task(self, task_name):
        """开始计时任务"""
        if self.current_task:
            self.stop_task()
        self.current_task = task_name
        self.start_time = datetime.now()
        if task_name not in self.tasks:
            self.tasks[task_name] = timedelta()
        print(f"▶ 开始任务: {task_name} ({self.start_time.strftime('%H:%M:%S')})")
    def stop_task(self):
        """停止当前任务"""
        if not self.current_task:
            return
        end_time = datetime.now()
        duration = end_time - self.start_time
        self.tasks[self.current_task] += duration
        print(f"⏹ 停止任务: {self.current_task}")
        print(f"   本次用时: {self._format_duration(duration)}")
        self.current_task = None
        self.start_time = None
    def _format_duration(self, duration):
        """格式化时间间隔"""
        total_seconds = int(duration.total_seconds())
        hours = total_seconds // 3600
        minutes = (total_seconds % 3600) // 60
        seconds = total_seconds % 60
        if hours > 0:
            return f"{hours}小时{minutes}分{seconds}秒"
        elif minutes > 0:
            return f"{minutes}分{seconds}秒"
        else:
            return f"{seconds}秒"
    def get_task_stats(self):
        """获取任务统计"""
        print("\n📊 项目时间统计")
        print("=" * 40)
        total_time = sum(self.tasks.values(), timedelta())
        for task, duration in sorted(self.tasks.items(), 
                                     key=lambda x: x[1], reverse=True):
            percentage = (duration / total_time * 100) if total_time else 0
            bar = '█' * int(percentage / 5)
            print(f"{task:15s} {self._format_duration(duration):10s} {bar} {percentage:.1f}%")
        print("=" * 40)
        print(f"总时间: {self._format_duration(total_time)}")
        return self.tasks
    def generate_report(self):
        """生成时间报告"""
        now = datetime.now()
        report = f"""
╔════════════════════════════════════╗
║        时间追踪报告                ║
╠════════════════════════════════════╣
║ 生成时间: {now.strftime('%Y-%m-%d %H:%M')}  ║
╠════════════════════════════════════╣
"""
        for task, duration in self.tasks.items():
            report += f"║  {task:20s} {self._format_duration(duration):10s}║\n"
        total = sum(self.tasks.values(), timedelta())
        report += f"╠════════════════════════════════════╣\n"
        report += f"║  总计: {self._format_duration(total):25s}║\n"
        report += "╚════════════════════════════════════╝\n"
        print(report)
# 使用示例
timer = ProjectTimer()
# 模拟不同任务
print("🎯 项目计时器演示")
print("-" * 30)
# 开始第一个任务
timer.start_task("需求分析")
time_module.sleep(1)  # 模拟工作
timer.stop_task()
# 开始第二个任务
timer.start_task("编码开发")
time_module.sleep(0.5)
timer.stop_task()
# 继续编码任务
timer.start_task("编码开发")
time_module.sleep(0.7)
timer.stop_task()
# 开始测试任务
timer.start_task("单元测试")
time_module.sleep(0.3)
timer.stop_task()
# 显示统计
timer.get_task_stats()
timer.generate_report()

案例5:日期运算 - 生日倒计时与纪念日计算

from datetime import date, datetime, timedelta
import calendar
class DateCalculator:
    """日期计算器:生日、纪念日、节日计算"""
    def __init__(self):
        self.events = {}
    def add_birthday(self, name, birth_date):
        """添加生日"""
        self.events[name] = {
            'type': 'birthday',
            'date': birth_date
        }
    def days_until_next_birthday(self, name):
        """计算距离下一个生日还有多少天"""
        if name not in self.events:
            return None
        birth_date = self.events[name]['date']
        today = date.today()
        # 今年的生日
        this_year_birthday = date(today.year, birth_date.month, birth_date.day)
        # 如果今年的生日已经过了,计算明年的
        if this_year_birthday < today:
            next_birthday = date(today.year + 1, birth_date.month, birth_date.day)
        else:
            next_birthday = this_year_birthday
        days_left = (next_birthday - today).days
        # 计算年龄
        age = next_birthday.year - birth_date.year
        return days_left, age
    def calculate_anniversary(self, start_date, years):
        """计算纪念日"""
        try:
            # 处理闰年2月29日的情况
            if start_date.month == 2 and start_date.day == 29:
                # 如果不是闰年,使用2月28日
                if not calendar.isleap(start_date.year + years):
                    return date(start_date.year + years, 2, 28)
            return date(start_date.year + years, 
                       start_date.month, start_date.day)
        except ValueError:
            return None
    def get_weekday_name(self, d):
        """获取星期几的中文名"""
        weekdays = ['星期一', '星期二', '星期三', 
                    '星期四', '星期五', '星期六', '星期日']
        return weekdays[d.weekday()]
    def get_month_calendar(self, year, month):
        """获取某个月的日历信息"""
        cal = calendar.monthcalendar(year, month)
        print(f"\n📅 {year}年{month}月日历")
        print("日  一  二  三  四  五  六")
        print("-" * 27)
        for week in cal:
            week_str = ""
            for day in week:
                if day == 0:
                    week_str += "    "
                else:
                    # 标记今天
                    if day == date.today().day and \
                       month == date.today().month and \
                       year == date.today().year:
                        week_str += f"[{day:2d}]"
                    else:
                        week_str += f" {day:2d} "
            print(week_str)
    def countdown_to_event(self, event_date, event_name):
        """事件倒计时"""
        today = date.today()
        days_left = (event_date - today).days
        if days_left > 0:
            print(f"⏳ 距离{event_name}还有 {days_left} 天")
        elif days_left == 0:
            print(f"🎉 今天就是{event_name}!")
        else:
            print(f"📝 {event_name}已经过去 {abs(days_left)} 天")
        # 更详细的倒计时
        if days_left > 0:
            hours = days_left * 24
            minutes = hours * 60
            seconds = minutes * 60
            print(f"   相当于 {hours} 小时, {minutes} 分钟, {seconds} 秒")
        return days_left
# 使用示例
calc = DateCalculator()
# 添加生日
print("=== 生日倒计时 ===")
calc.add_birthday("小明", date(1995, 4, 15))
calc.add_birthday("小红", date(1998, 12, 25))
for name in ["小明", "小红"]:
    days_left, age = calc.days_until_next_birthday(name)
    if days_left:
        print(f"{name}将在 {days_left} 天后过{age}岁生日")
# 计算纪念日
print("\n=== 纪念日计算 ===")
start_date = date(2020, 1, 1)  # 开始日期
print(f"开始日期: {start_date} ({calc.get_weekday_name(start_date)})")
for years in [1, 3, 5]:
    anniversary = calc.calculate_anniversary(start_date, years)
    if anniversary:
        print(f"{years}周年纪念日: {anniversary} ({calc.get_weekday_name(anniversary)})")
# 显示月份日历
print("\n=== 本月日历 ===")
today = date.today()
calc.get_month_calendar(today.year, today.month)
# 事件倒计时
print("\n=== 事件倒计时 ===")
# 设置一个未来日期
future_date = date(today.year, 12, 31)  # 今年的最后一天
if future_date < today:
    future_date = date(today.year + 1, 12, 31)
calc.countdown_to_event(future_date, "跨年")
# 计算工作日相关
print("\n=== 工作日信息 ===")
current_month = today.month
current_year = today.year
# 获取本月的工作日数量
_, days_in_month = calendar.monthrange(current_year, current_month)
workdays = sum(1 for day in range(1, days_in_month + 1)
               if calendar.weekday(current_year, current_month, day) < 5)
print(f"{current_year}年{current_month}月工作日: {workdays}天")

关键知识点总结

核心类

  • datetime: 日期和时间组合
  • date: 仅日期(年、月、日)
  • time: 仅时间(时、分、秒、微秒)
  • timedelta: 时间间隔
  • timezone: 时区处理

常用操作

# 获取当前时间
now = datetime.now()
# 创建特定时间
specific = datetime(2024, 4, 5, 14, 30, 0)
# 时间运算
future = now + timedelta(days=7, hours=3)
# 时间比较
if now < future:
    print("未来时间")
# 格式化
formatted = now.strftime('%Y-%m-%d %H:%M:%S')
# 解析字符串
parsed = datetime.strptime('2024-04-05', '%Y-%m-%d')

常见格式代码

代码 说明 示例
%Y 4位年份 2024
%m 2位月份 04
%d 2位日期 05
%H 24小时制 14
%M 分钟 30
%S 00
%w 星期几 0(周日)

实用技巧

# 获取本月天数
_, days = calendar.monthrange(2024, 4)
# 检查闰年
calendar.isleap(2024)
# 获取星期几
date_obj.weekday()  # 0=周一,6=周日
date_obj.isoweekday()  # 1=周一,7=周日
# 时间戳转换
timestamp = datetime.now().timestamp()
dt = datetime.fromtimestamp(timestamp)
# 时区转换
from zoneinfo import ZoneInfo
utc_time = datetime.now(ZoneInfo('UTC'))
local_time = utc_time.astimezone(ZoneInfo('Asia/Shanghai'))

通过以上案例,你可以看到 datetime 模块在日程管理、日志分析、时区转换、项目跟踪和日期计算等方面的实际应用,建议尝试修改这些案例中的参数,添加新功能,来加深理解。

标签: datetime Python

抱歉,评论功能暂时关闭!