本文目录导读:

我来分享几个常用的Python时间工具封装案例:
基础时间工具类
from datetime import datetime, timedelta, date
import time
import calendar
from typing import Optional, Union, List
import pytz
class TimeUtils:
"""时间工具类"""
# 时间格式常量
FORMAT_DATETIME = "%Y-%m-%d %H:%M:%S"
FORMAT_DATE = "%Y-%m-%d"
FORMAT_TIME = "%H:%M:%S"
FORMAT_TIMESTAMP = "%Y%m%d%H%M%S"
@staticmethod
def get_now(format_str: str = FORMAT_DATETIME) -> str:
"""获取当前时间字符串"""
return datetime.now().strftime(format_str)
@staticmethod
def get_timestamp() -> float:
"""获取当前时间戳"""
return time.time()
@staticmethod
def format_datetime(dt: datetime, format_str: str = FORMAT_DATETIME) -> str:
"""格式化datetime对象"""
return dt.strftime(format_str)
@staticmethod
def parse_datetime(time_str: str, format_str: str = FORMAT_DATETIME) -> datetime:
"""解析时间字符串为datetime对象"""
return datetime.strptime(time_str, format_str)
时间计算工具
class TimeCalculator:
"""时间计算工具类"""
@staticmethod
def add_days(dt: datetime, days: int) -> datetime:
"""增加天数"""
return dt + timedelta(days=days)
@staticmethod
def add_hours(dt: datetime, hours: int) -> datetime:
"""增加小时"""
return dt + timedelta(hours=hours)
@staticmethod
def add_minutes(dt: datetime, minutes: int) -> datetime:
"""增加分钟"""
return dt + timedelta(minutes=minutes)
@staticmethod
def date_range(start: datetime, end: datetime, step: int = 1) -> List[datetime]:
"""生成日期范围"""
dates = []
current = start
while current <= end:
dates.append(current)
current += timedelta(days=step)
return dates
@staticmethod
def time_difference(start: datetime, end: datetime) -> dict:
"""计算时间差"""
diff = end - start
days = diff.days
seconds = diff.seconds
hours = seconds // 3600
minutes = (seconds % 3600) // 60
secs = seconds % 60
return {
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': secs,
'total_seconds': diff.total_seconds()
}
时间戳工具
class TimestampUtils:
"""时间戳工具类"""
@staticmethod
def datetime_to_timestamp(dt: datetime) -> float:
"""datetime转时间戳"""
return dt.timestamp()
@staticmethod
def timestamp_to_datetime(timestamp: float) -> datetime:
"""时间戳转datetime"""
return datetime.fromtimestamp(timestamp)
@staticmethod
def string_to_timestamp(time_str: str, format_str: str = TimeUtils.FORMAT_DATETIME) -> float:
"""时间字符串转时间戳"""
dt = datetime.strptime(time_str, format_str)
return dt.timestamp()
@staticmethod
def timestamp_to_string(timestamp: float, format_str: str = TimeUtils.FORMAT_DATETIME) -> str:
"""时间戳转字符串"""
dt = datetime.fromtimestamp(timestamp)
return dt.strftime(format_str)
时区工具
class TimezoneUtils:
"""时区工具类"""
@staticmethod
def get_timezone_time(timezone_name: str = 'Asia/Shanghai') -> datetime:
"""获取指定时区的时间"""
tz = pytz.timezone(timezone_name)
return datetime.now(tz)
@staticmethod
def convert_timezone(dt: datetime, from_tz: str, to_tz: str) -> datetime:
"""转换时区"""
from_timezone = pytz.timezone(from_tz)
to_timezone = pytz.timezone(to_tz)
# 如果datetime没有时区信息,先添加
if dt.tzinfo is None:
dt = from_timezone.localize(dt)
return dt.astimezone(to_timezone)
@staticmethod
def list_timezones(keyword: str = '') -> List[str]:
"""列出时区列表"""
all_timezones = pytz.all_timezones
if keyword:
return [tz for tz in all_timezones if keyword.lower() in tz.lower()]
return all_timezones
月份和日期工具
class MonthDayUtils:
"""月份和日期工具类"""
@staticmethod
def get_month_days(year: int, month: int) -> int:
"""获取某月的天数"""
return calendar.monthrange(year, month)[1]
@staticmethod
def is_leap_year(year: int) -> bool:
"""判断是否为闰年"""
return calendar.isleap(year)
@staticmethod
def get_weekday(year: int, month: int, day: int) -> str:
"""获取星期几"""
weekdays = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
weekday_num = datetime(year, month, day).weekday()
return weekdays[weekday_num]
@staticmethod
def get_first_day_of_month(year: int, month: int) -> datetime:
"""获取月初"""
return datetime(year, month, 1)
@staticmethod
def get_last_day_of_month(year: int, month: int) -> datetime:
"""获取月末"""
last_day = calendar.monthrange(year, month)[1]
return datetime(year, month, last_day)
实用装饰器
import functools
def timer_decorator(func):
"""函数执行时间计时器"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__} 执行耗时: {end_time - start_time:.4f} 秒")
return result
return wrapper
def retry_decorator(max_retries=3, delay=1):
"""重试装饰器(带延迟)"""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for i in range(max_retries):
try:
return func(*args, **kwargs)
except Exception as e:
if i == max_retries - 1:
raise
print(f"重试 {i+1}/{max_retries}: {e}")
time.sleep(delay)
return None
return wrapper
return decorator
使用示例
# 使用示例
if __name__ == "__main__":
# 基础使用
print("当前时间:", TimeUtils.get_now())
print("时间戳:", TimeUtils.get_timestamp())
# 时间计算
calculator = TimeCalculator()
now = datetime.now()
print("7天后:", TimeUtils.format_datetime(calculator.add_days(now, 7)))
# 时间差
start = datetime(2024, 1, 1)
end = datetime(2024, 12, 31)
diff = calculator.time_difference(start, end)
print(f"相差: {diff['days']}天, {diff['hours']}小时")
# 时区转换
tz_utils = TimezoneUtils()
beijing_time = tz_utils.get_timezone_time('Asia/Shanghai')
print("北京时间:", beijing_time)
# 装饰器使用
@timer_decorator
def test_function():
time.sleep(1)
return "完成"
result = test_function()
安装依赖
pip install pytz # 时区支持
这些工具封装了常用的时间操作,可以根据实际需求进行扩展和修改。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播