from datetime import datetime import time from typing import Optional import pytz # 需要先安装: pip install pytz 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 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}"