crypto.ai/cryptoai/utils/db_utils.py
2025-05-24 12:08:57 +08:00

36 lines
988 B
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.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
from typing import Optional, Union
from datetime import datetime
# 配置日志
logger = logging.getLogger('db_utils')
def convert_timestamp_to_datetime(timestamp: Union[int, float, str, None]) -> Optional[datetime]:
"""
将时间戳转换为datetime对象
Args:
timestamp: Unix时间戳毫秒级
Returns:
datetime对象或None
"""
if timestamp is None:
return None
try:
# 转换为整数
if isinstance(timestamp, str):
timestamp = int(timestamp)
# 如果是毫秒级时间戳,转换为秒级
if timestamp > 1e11: # 判断是否为毫秒级时间戳
timestamp = timestamp / 1000
return datetime.fromtimestamp(timestamp)
except (ValueError, TypeError) as e:
logger.error(f"时间戳转换失败: {timestamp}, 错误: {e}")
return None