deliveryman-api/app/core/utils.py
2025-03-12 12:40:43 +08:00

81 lines
2.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from datetime import datetime
import time
from typing import Optional, List
import pytz # 需要先安装: pip install pytz
import re
class CommonUtils:
"""工具类"""
@staticmethod
def get_asia_datetime(my_datetime: datetime, timezone='Asia/Shanghai') -> str:
"""
将时间转换为UTF-8编码
"""
tz = pytz.timezone(timezone)
return my_datetime.astimezone(tz).strftime('%Y-%m-%d %H:%M:%S')
@staticmethod
def get_current_time(timezone='Asia/Shanghai') -> str:
"""
获取指定时区的当前时间
:param timezone: 时区名称,默认为上海时区(东八区)
"""
tz = pytz.timezone(timezone)
return datetime.now(tz).strftime('%Y-%m-%d %H:%M:%S')
@staticmethod
def generate_order_id(prefix: str) -> str:
"""
生成订单号
:param prefix: 订单前缀,如 M(商品订单)、P(支付订单)、D(配送订单)、E(积分兑换商品订单)
:return: 15位订单号前缀(1位) + 日期(8位) + 时间戳(6位)
"""
now = datetime.now()
date_str = now.strftime('%Y%m%d')
# 取时间戳后6位
timestamp = str(int(time.time() * 1000))[-6:]
return f"{prefix}{date_str}{timestamp}"
@staticmethod
def desensitize_phone(phone: str) -> str:
"""
手机号脱敏
"""
return f"{phone[:3]}****{phone[7:]}"
@staticmethod
def generate_verify_code() -> str:
"""
生成核销码
:return: 16位数字核销码日期(8位) + 时间戳(8位)
"""
now = datetime.now()
date_str = now.strftime('%Y%m%d')
timestamp = str(int(time.time() * 1000))[-8:]
return f"{date_str}{timestamp}"
@staticmethod
def extract_first_number(s: str) -> int:
"""
提取字符串中的第一个数字
如果没有数字返回0
"""
try:
# 使用正则表达式匹配第一个数字
match = re.search(r'\d+', s)
return int(match.group()) if match else 0
except:
return 0
@staticmethod
def sort_strings_by_first_number(strings: List[str]) -> List[str]:
"""
按第一个数字排序字符串数组
"""
try:
return sorted(strings, key=CommonUtils.extract_first_number)
except Exception as e:
print(f"排序出错: {str(e)}")
return strings # 出错时返回原数组