Table of Contents
Introduction
Function
Code packaging
Example Demo:
Home Backend Development Python Tutorial How to encapsulate the Python time processing library and create your own TimeUtil class

How to encapsulate the Python time processing library and create your own TimeUtil class

May 12, 2023 am 11:55 AM
python

Introduction

In daily Python development, the need to deal with time and date is very common. Although Python has built-in datetime and time modules, they may not be intuitive and easy to use in some cases. To solve this problem, we encapsulate a time processing class called TimeUtil to simplify common time-related tasks by providing an easy-to-use set of methods.

Function

  • Time addition and subtraction: TimeUtil supports adding or subtracting years, months, days, hours, minutes and seconds based on datetime objects.

  • Calculate the date yesterday, tomorrow, one week from now and one month from now.

  • Convert a string to a datetime object.

  • Convert datetime object to string.

  • Convert timestamp to time in string format.

  • Convert the time in string format to a timestamp.

  • Convert timestamp to datetime object.

  • The difference between two times (datetime objects)

  • Calculate the number of working days

Code packaging

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Author: Hui
# @Desc: { 时间工具类模块 }
# @Date: 2022/11/26 16:08
import time
from datetime import datetime
from typing import Union
from dateutil.relativedelta import relativedelta
from enums import TimeFormatEnum, TimeUnitEnum
class TimeUtil(object):
    """时间工具类"""
    UNITS_IN_SECONDS = {
        TimeUnitEnum.DAYS: 86400,
        TimeUnitEnum.HOURS: 3600,
        TimeUnitEnum.MINUTES: 60,
        TimeUnitEnum.SECONDS: 1,
    }
    def __init__(self, datetime_obj: datetime = None, format_str: str = TimeFormatEnum.DateTime.value):
        """
        时间工具类初始化
        Args:
            datetime_obj: 待处理的datetime对象,不传时默认取当前时间
            format_str: 时间格式化字符串
        """
        self.datetime_obj = datetime_obj or datetime.now()
        self.format_str = format_str
    @property
    def yesterday(self) -> datetime:
        """获取昨天的日期"""
        return self.sub_time(days=1)
    @property
    def tomorrow(self) -> datetime:
        """获取明天的日期"""
        return self.add_time(days=1)
    @property
    def week_later(self) -> datetime:
        """获取一周后的日期"""
        return self.add_time(days=7)
    @property
    def month_later(self) -> datetime:
        """获取一个月后的日期"""
        return self.add_time(months=1)
    def add_time(self, years=0, months=0, days=0, hours=0, minutes=0, seconds=0, **kwargs) -> datetime:
        """增加指定时间"""
        return self.datetime_obj + relativedelta(
            years=years, months=months, days=days, hours=hours, minutes=minutes, seconds=seconds, **kwargs
        )
    def sub_time(self, years=0, months=0, days=0, hours=0, minutes=0, seconds=0, **kwargs) -> datetime:
        """减去指定时间"""
        return self.datetime_obj - relativedelta(
            years=years, months=months, days=days, hours=hours, minutes=minutes, seconds=seconds, **kwargs
        )
    def str_to_datetime(self, date_str: str, format_str: str = None) -> datetime:
        """将时间字符串转换为 datetime 对象"""
        format_str = format_str or self.format_str
        return datetime.strptime(date_str, format_str)
    def datetime_to_str(self, format_str: str = None) -> str:
        """将 datetime 对象转换为时间字符串"""
        format_str = format_str or self.format_str
        return self.datetime_obj.strftime(format_str)
    def timestamp_to_str(self, timestamp: float, format_str: str = None) -> str:
        """将时间戳转换为时间字符串"""
        format_str = format_str or self.format_str
        return datetime.fromtimestamp(timestamp).strftime(format_str)
    def str_to_timestamp(self, time_str: str, format_str: str = None) -> float:
        """将时间字符串转换为时间戳"""
        format_str = format_str or self.format_str
        return time.mktime(time.strptime(time_str, format_str))
    @staticmethod
    def timestamp_to_datetime(timestamp: float) -> datetime:
        """将时间戳转换为 datetime 对象"""
        return datetime.fromtimestamp(timestamp)
    @property
    def timestamp(self) -> float:
        """获取 datetime 对象的时间戳"""
        return self.datetime_obj.timestamp()
    def difference(self, other_datetime_obj: datetime, unit: Union[TimeUnitEnum, str] = TimeUnitEnum.DAYS) -> int:
        """
        计算两个日期之间的差值
        Args:
            other_datetime_obj: 另一个 datetime 对象
            unit: 时间单位
        Raises:
            ValueError: 如果传入unit不在枚举范围内,会抛出ValueError异常
        Returns:
            两个日期之间的差值,以指定的单位表示
        """
        if isinstance(unit, str):
            unit = TimeUnitEnum(unit)
        delta = abs(self.datetime_obj - other_datetime_obj)
        return int(delta.total_seconds() // self.UNITS_IN_SECONDS[unit])
    def difference_in_detail(self, datetime_obj: datetime):
        """
        计算两个日期之间的差值详情
        Args:
            datetime_obj: 时间对象
        Returns: DateDiff
        """
        delta = relativedelta(self.datetime_obj, datetime_obj)
        return DateDiff(
            years=abs(delta.years),
            months=abs(delta.months),
            days=abs(delta.days),
            hours=abs(delta.hours),
            minutes=abs(delta.minutes),
            seconds=abs(delta.seconds),
        )
    def count_weekdays_between(self, datetime_obj: datetime, include_end_date: bool = True) -> int:
        """计算两个日期之间的工作日数量
        Args:
            datetime_obj: datetime 对象
            include_end_date: 是否包含结束日期(默认为 True)
        Returns:
            两个日期之间的工作日数量
        """
        # 确保 start_date 是较小的日期,end_date 是较大的日期
        start_date = min(self.datetime_obj, datetime_obj)
        end_date = max(self.datetime_obj, datetime_obj)
        # 如果不包含结束日期,将 end_date 减去一天
        if not include_end_date:
            end_date = end_date - relativedelta(days=1)
        # 计算两个日期之间的天数
        days_between = abs((end_date - start_date).days)
        # 计算完整周数,每周有5个工作日
        weeks_between = days_between // 7
        weekdays = weeks_between * 5
        # 计算剩余的天数
        remaining_days = days_between % 7
        # 遍历剩余的天数,检查每天是否为工作日,如果是,则累加工作日数量
        for day_offset in range(remaining_days + 1):
            if (start_date + relativedelta(days=day_offset)).weekday() < 5:
                weekdays += 1
        return weekdays
Copy after login

Example Demo:

The following are some examples of using the TimeUtil library:

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Author: Hui
# @Desc: { 时间工具类案例 }
# @Date: 2023/04/30 21:08
import time
from datetime import datetime
from utils.time import TimeUtil
# 创建一个TimeUtil实例,默认使用当前时间
time_util = TimeUtil()
print("昨天的日期:", time_util.yesterday)
print("明天的日期:", time_util.tomorrow)
print("一周后的日期:", time_util.week_later)
print("一个月后的日期:", time_util.month_later)
>>>out
昨天的日期: 2023-04-29 21:10:56.642787
明天的日期: 2023-05-01 21:10:56.642787
一周后的日期: 2023-05-07 21:10:56.642787
一个月后的日期: 2023-05-30 21:10:56.642787
Copy after login

The property decorator is used here to allow some methods to get the most recent date. It becomes the same as getting the attribute value, and it becomes more concise to use.

# 从现在开始增加10天
print("10天后的日期:", time_util.add_time(days=10))
# 从现在开始减少5天
print("5天前的日期:", time_util.sub_time(days=5))
>>>out
10天后的日期: 2023-05-10 21:28:35.587173
5天前的日期: 2023-04-25 21:28:35.587173
Copy after login

add_time, sub_time are methods to specifically implement time (datetime object) addition and subtraction operations, mainly through the relativedelta of the python-dateutil library to encapsulate it, compared to the built-in timedelta The difference between years and months can be calculated more accurately.

# 将日期字符串转换为datetime对象
date_str = "2023-05-01 12:00:00"
print("字符串转换为datetime对象:", time_util.str_to_datetime(date_str))
# 将datetime对象转换为日期字符串
print("datetime对象转换为字符串:", time_util.datetime_to_str())
# 将时间戳转换为时间字符串
timestamp = time.time()
print("时间戳转换为时间字符串:", time_util.timestamp_to_str(timestamp))
# 将时间字符串转换为时间戳
time_str = "2023-05-01 12:00:00"
print("时间字符串转换为时间戳:", time_util.str_to_timestamp(time_str))
# 将时间戳转换为datetime对象
print("时间戳转换为datetime对象:", time_util.timestamp_to_datetime(timestamp))
# 获取当前时间的时间戳
print("当前时间的时间戳:", time_util.timestamp)
>>>out
字符串转换为datetime对象: 2023-05-01 12:00:00
datetime对象转换为字符串: 2023-04-30 21:28:35
时间戳转换为时间字符串: 2023-04-30 21:28:35
时间字符串转换为时间戳: 1682913600.0
时间戳转换为datetime对象: 2023-04-30 21:28:35.589926
当前时间的时间戳: 1682861315.587173
Copy after login

This section is the most commonly used methods for converting time strings, timestamps, and datetime objects to each other.

# 获取两个日期之间的差值
time_util = TimeUtil(datetime_obj=datetime(2023, 4, 24, 10, 30, 0))
datetime_obj = datetime(2023, 4, 29, 10, 30, 0)
delta_days = time_util.difference(datetime_obj, unit="days")
delta_hours = time_util.difference(datetime_obj, unit="hours")
delta_minutes = time_util.difference(datetime_obj, unit=TimeUnitEnum.MINUTES)
delta_seconds = time_util.difference(datetime_obj, unit=TimeUnitEnum.SECONDS)
print(f"两个日期之间相差的天数: {delta_days}")
print(f"两个日期之间相差的小时数: {delta_hours}")
print(f"两个日期之间相差的分钟数: {delta_minutes}")
print(f"两个日期之间相差的秒数: {delta_seconds}")
>>>out
两个日期之间相差的天数: 5
两个日期之间相差的小时数: 120
两个日期之间相差的分钟数: 7200
两个日期之间相差的秒数: 432000
Copy after login
date1 = datetime(2023, 4, 24)  # 2023年4月24日,星期一
date2 = datetime(2023, 5, 1)  # 2023年5月1日,星期一
time_util = TimeUtil(datetime_obj=date1)
# 计算两个日期之间的工作日数量
weekday_count = time_util.count_weekdays_between(date2, include_end_date=True)
print(f"从 {date1} 到 {date2} 之间有 {weekday_count} 个工作日。(包含末尾日期)")
weekday_count = time_util.count_weekdays_between(date2, include_end_date=False)
print(f"从 {date1} 到 {date2} 之间有 {weekday_count} 个工作日。(不包含末尾日期)")
date_diff = time_util.difference_in_detail(date2)
print(date_diff)
>>>out
从 2023-04-24 00:00:00 到 2023-05-01 00:00:00 之间有 6 个工作日。(包含末尾日期)
从 2023-04-24 00:00:00 到 2023-05-01 00:00:00 之间有 5 个工作日。(不包含末尾日期)
DateDiff(years=0, months=0, days=7, hours=0, minutes=0, seconds=0)
Copy after login

The last step is to calculate the difference based on the two time objects, calculate the number of working days, etc.

The above is the detailed content of How to encapsulate the Python time processing library and create your own TimeUtil class. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1272
29
C# Tutorial
1252
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles