ak13/util.py
cheney fcf9b977fb
All checks were successful
Build and Push Docker Image / build-and-push (push) Successful in 1m42s
拆分 day 和 hour 逻辑
2025-07-22 15:32:00 +08:00

61 lines
2.0 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.

import datetime
import akshare as ak
def is_trading_time_akshare(current_time=None):
"""
使用akshare判断当前是否为A股开市时间包括交易日和交易时段
参数:
current_time: 待判断的时间,默认为当前时间
返回:
bool: 是否为开市状态
"""
if current_time is None:
current_time = datetime.datetime.now()
# 获取当前日期字符串YYYY-MM-DD
current_date_str = current_time.strftime("%Y-%m-%d")
# 获取A股历史交易日数据包含所有交易日
trade_dates = ak.tool_trade_date_hist_sina()
# 1. 判断是否为交易日
is_trading_day = current_date_str in trade_dates["trade_date"].values
if not is_trading_day:
return False
# 2. 判断是否在交易时间段内
# 上午9:30-11:30下午13:00-15:00
current_time_of_day = current_time.time()
morning_start = datetime.time(9, 30)
morning_end = datetime.time(11, 30)
afternoon_start = datetime.time(13, 0)
afternoon_end = datetime.time(15, 0)
in_morning = morning_start <= current_time_of_day <= morning_end
in_afternoon = afternoon_start <= current_time_of_day <= afternoon_end
return in_morning or in_afternoon
if __name__ == "__main__":
now = datetime.datetime.now()
print(f"当前时间: {now.strftime('%Y-%m-%d %H:%M:%S')}")
print(f"是否为开市时间: {'' if is_trading_time_akshare() else ''}")
# 测试特定时间
test_times = [
datetime.datetime(2023, 10, 9, 10, 0), # 交易日上午
datetime.datetime(2023, 10, 9, 14, 0), # 交易日下午
datetime.datetime(2023, 10, 9, 8, 0), # 交易日前早
datetime.datetime(2023, 10, 7, 10, 0), # 周六
datetime.datetime(2023, 10, 1, 10, 0), # 国庆假期
]
print("\n测试特定时间:")
for test_time in test_times:
status = "" if is_trading_time_akshare(test_time) else ""
print(f"{test_time.strftime('%Y-%m-%d %H:%M')}: {status}")