crypto_quant/core/utils.py

30 lines
1.1 KiB
Python
Raw Normal View History

2025-07-24 10:23:00 +00:00
from datetime import datetime, timezone, timedelta
2025-07-25 08:12:52 +00:00
from decimal import Decimal
2025-07-24 10:23:00 +00:00
def datetime_to_timestamp(date_str: str) -> int:
"""
将日期字符串 '2023-01-01 12:00:00'直接转换为毫秒级时间戳
:param date_str: 形如 '2023-01-01 12:00:00' 的日期时间字符串
:return: 毫秒级时间戳
"""
dt = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')
return int(dt.timestamp() * 1000)
def timestamp_to_datetime(timestamp: int) -> str:
"""
将时间戳转换为日期字符串
请考虑日期字符串位于北京时区
:param timestamp: 以毫秒为单位的时间戳
:return: 形如 '2023-01-01 12:00:00' 的日期时间字符串
"""
dt = datetime.fromtimestamp(timestamp / 1000, timezone(timedelta(hours=8)))
2025-07-25 08:12:52 +00:00
return dt.strftime('%Y-%m-%d %H:%M:%S')
def transform_data_type(data: dict):
"""
遍历字典将所有Decimal类型的值转换为float类型
"""
for key, value in data.items():
if isinstance(value, Decimal):
data[key] = float(value)
return data