crypto_quant/core/utils.py

45 lines
1.5 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
import re
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
def check_date_time_format(date_time: str) -> bool:
"""
检查日期时间格式是否正确
"""
if re.match(r'^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$', date_time):
return date_time
elif re.match(r'^\d{4}-\d{2}-\d{2}$', date_time):
return date_time + " 00:00:00"
elif re.match(r'^\d{4}\d{2}\d{2}$', date_time):
return f"{date_time[0:4]}-{date_time[4:6]}-{date_time[6:8]} 00:00:00"
else:
return None