crypto_quant/core/utils.py

30 lines
1.1 KiB
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.

from datetime import datetime, timezone, timedelta
from decimal import Decimal
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)))
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