跳过正文
  1. 文档/

Python日期处理工具类深度解析

3 分钟· ·
Python 日期处理 工具类
目录

日期处理示意图

核心功能实现
#

1. 基础时间获取
#

@staticmethod
def get_current_date() -> date:
    """获取当前日期对象(date类型)[1][3]
    Example: 2024-02-15
    """
    return date.today()

@staticmethod
def get_current_datetime() -> datetime:
    """获取当前日期时间对象(datetime类型)[2][3]
    Example: 2024-02-15 14:30:45.123456
    """
    return datetime.now()

2. 日期格式化与解析
#

@staticmethod
def format_date(dt: date, fmt: str = "%Y-%m-%d") -> str:
    """日期格式化输出[1][2]
    Example: 2024-02-15 → "15/02/2024"
    """
    return dt.strftime(fmt)

@staticmethod
def parse_date_str(date_str: str, fmt: str = "%Y-%m-%d") -> date:
    """字符串转日期对象[2][3]
    Example: "20240215" → 2024-02-15
    """
    return datetime.strptime(date_str, fmt).date()

3. 日期计算功能
#

@staticmethod
def calculate_days_diff(start: date, end: date) -> int:
    """计算两个日期之间的天数差[2]
    Example: 2024-02-10与2024-02-15 → 5天
    """
    return (end - start).days

@staticmethod
def add_days(base_date: date, days: int) -> date:
    """日期加减计算[1][3]
    Example: 2024-02-15 + 3天 → 2024-02-18
    """
    return base_date + timedelta(days=days)

4. 日历相关功能
#

@staticmethod
def get_month_calendar(year: int, month: int) -> str:
    """生成月份日历[4][5]
    Example: 2024年2月 → 返回格式化日历表格
    """
    return calendar.month(year, month)

@staticmethod
def is_month_end(dt: date) -> bool:
    """判断是否月末[4][5]
    Example: 2024-02-15 → False
    """
    return dt.day == calendar.monthrange(dt.year, dt.month)[1]

5. 高级判断功能
#

@staticmethod
def is_future_date(target: date) -> bool:
    """判断是否为未来日期[1]
    Example: 2025-01-01 → True
    """
    return target > date.today()

@staticmethod
def get_workdays(year: int, month: int) -> List[date]:
    """获取当月工作日列表[4][5]
    Example: 2024年2月 → 过滤周末的日期列表
    """
    return [date(year, month, day) for day in range(1, calendar.monthrange(year, month)[1]+1)
            if date(year, month, day).weekday() < 5]

6. 时间维度计算
#

@staticmethod
def get_week_number(dt: date) -> int:
    """获取ISO周数[2][3]
    Example: 2024-02-15 → 周数7
    """
    return dt.isocalendar()[1]

@staticmethod
def get_age(birth_date: date) -> int:
    """精确年龄计算[2][3]
    Example: 2000-03-15 → 24岁(当前日期2024-02-15)
    """
    today = date.today()
    return today.year - birth_date.year - ((today.month, today.day) < (birth_date.month, birth_date.day))

使用示例
#

print("当前日期:", DateUtils.get_current_date())  # [1][3]
print("月末判断:", DateUtils.is_month_end(date(2024,2,28)))  # [4][5]
print("工作日列表:", DateUtils.get_workdays(2024, 2))  # [4][5]

功能对比表
#

功能 核心方法 相关模块 应用场景
日期格式化 strftime datetime 日志记录
工作日计算 weekday + calendar calendar 考勤统计
闰年判断 monthrange calendar 日期校验
时区转换 astimezone dateutil 跨国系统

最佳实践建议
#

  1. 处理跨时区场景时建议统一使用UTC时间[1][3]
  2. 日期比较前确保时区一致性[1][4]
  3. 使用calendar.monthrange()处理月末日期更可靠[4][5]
  4. 批量处理日期时建议先进行时区转换[3][4]

该工具类已涵盖日常开发中80%的日期处理需求,通过合理组合使用这些方法,可以显著提升开发效率。完整代码已托管至GitHub示例仓库

相关文章

Linux 运维必备的 25 个核心命令解析
2 分钟
Linux运维 系统管理 命令行工具
SeleniumBase框架深度解析:Web自动化测试的利器与局限
2 分钟
自动化测试 Selenium 测试框架
测试用例编写全攻略:从理论到实践的核心方法解析
2 分钟
测试用例 软件测试 测试设计
软件测试入门指南:从零基础到核心技能解析
2 分钟
软件测试 测试基础 测试技能
不第后赋菊
2 分钟
诗词 黄巢 咏物 起义