You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用datetime判断美股是否开盘的逻辑异常问题

问题原因

你的判断条件里的逻辑运算符使用错误,这是导致周末也判定开盘的核心原因:
你写的判断逻辑是 (day_of_week != "Saturday" or day_of_week != "Sunday"),这个表达式的结果永远为True:

  • 若当天是周日:day_of_week != "Saturday" 结果为真,or逻辑只要有一个条件为真,整体结果就为真
  • 若当天是周六:day_of_week != "Sunday" 结果为真,整体结果同样为真
  • 若当天是工作日:两个条件都为真,整体结果还是真
    相当于这个周末判断的逻辑完全没有生效,只要时间在9:30到16:00之间,就会判定为开盘。
修复方案

将条件里的or改为and即可,修改后的判断逻辑为:
if 930 <= dt_east <= 1600 and (day_of_week != "Saturday" and day_of_week != "Sunday"):

代码优化建议

你可以提前把转换后的美东时间存为变量,避免重复调用时区转换方法,既提升效率也避免极端场景下的时间不一致问题,优化后的完整代码如下:

import datetime
import pytz

# 一次转换得到美东时间对象,后续直接复用
est_time = datetime.datetime.now(pytz.timezone('US/Eastern'))
local_date = datetime.datetime.strftime(datetime.datetime.now(), '%b %d, %Y')
print("Today's date is: " + str(local_date))

eastern_time = est_time.strftime('%I:%M %p')
print("Time on the East Coast is currently: " + eastern_time)
day_of_week = est_time.strftime('%A')
print(day_of_week)
dt_east = est_time.hour * 100 + est_time.minute
print(dt_east)

# 用not in写法更简洁易读
if 930 <= dt_east <= 1600 and day_of_week not in ("Saturday", "Sunday"):
    print("The market is open!")
else:
    print("The market is closed.")

内容的提问来源于stack exchange,提问作者squarehammer89

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 07:54:04