36 lines
988 B
Python
36 lines
988 B
Python
#!/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 |