Python |使用datetime判断美股是否开盘,逻辑不正确

Python | Using datetime to determine whether the US stock market is open, logic not working correctly

我有这段代码应该提到股票市场是否开放。节假日尚未包括在内。

current_time = datetime.now()
local_date = datetime.strftime(current_time, '%b %d, %Y')
print("Today's date is: " + str(local_date))

#Prints out the time on the east coast. Helps give context on market hours.    
eastern_time = datetime.strftime(current_time.astimezone(pytz.timezone('US/Eastern')), '%I:%M %p')

print("Time on the East Coast is currently: " + eastern_time)
day_of_week = datetime.strftime(current_time.astimezone(pytz.timezone('US/Eastern')), '%A')
print(day_of_week)
dt_east = int(datetime.strftime(current_time.astimezone(pytz.timezone('US/Eastern')), '%H%M'))
print(dt_east)
if 930 <= dt_east <= 1600 and (day_of_week != "Saturday" or day_of_week != "Sunday"):
    print("The market is open!")
else:
    print("The market is closed.")

  

输出:

Today's date is: Nov 07, 2021
Time on the East Coast is currently: 12:01 PM
Sunday
1213
The market is open!

打印出来 day_of_week 甚至显示今天是星期天,但 returns 市场是开市的。我 运行 快速 True/False 测试并且它 returns 是的,实际上是星期天。 不确定还能尝试什么。

# consider the below portion of your if 
(day_of_week != "Saturday" or day_of_week != "Sunday")

它 returns True 如果 day_of_week != "Saturday"day_of_week != "Sunday"True.

这意味着,如果这一天是 Sundayday_of_week != "Saturday" 仍然是 return True 所以总输出仍然是 True

您需要将 or 替换为 and

# if 930 <= dt_east <= 1600 and (day_of_week != "Saturday" or day_of_week != "Sunday")
if (930 <= dt_east <= 1600) and (day_of_week != "Saturday") and (day_of_week != "Sunday")