"""时间戳解析器"""
import logging
from datetime import datetime
from typing import Any
import pytz
from jsonschema import TypeChecker
from apps.schemas.enum_var import SlotType
logger = logging.getLogger(__name__)
class SlotTimestampParser:
"""时间戳解析器"""
type: SlotType = SlotType.TYPE
name: str = "timestamp"
@classmethod
def convert(cls, data: str | int, **_kwargs) -> str:
"""将日期字符串转换为日期对象"""
try:
timestamp_int = int(data)
return datetime.fromtimestamp(timestamp_int, tz=pytz.timezone("Asia/Shanghai")).strftime(
"%Y-%m-%d %H:%M:%S",
)
except Exception:
logger.exception("[SlotTimestampParser] Timestamp解析失败")
return str(data)
@classmethod
def type_validate(cls, _checker: TypeChecker, instance: Any) -> bool:
"""
生成type的验证器
若没有对应的处理逻辑则返回True
"""
if not isinstance(instance, (str, int, float)):
return False
try:
timestamp_int = int(instance)
datetime.fromtimestamp(timestamp_int, tz=pytz.timezone("Asia/Shanghai"))
except Exception:
logger.exception("[SlotTimestampParser] Timestamp验证失败: %s", instance)
return False
return True