Home > Article > Backend Development > How to encapsulate the Python time processing library and create your own TimeUtil class
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.
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
#!/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
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
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
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
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
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)
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!