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

I have this block of code that is supposed to be mentioning whether the stock market is open or not. Holidays aren’t included yet.

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.")

  

Output:

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

Printing out day_of_week even shows that it’s Sunday but returns that the market is open. I ran a quick True/False test and it returns True that it is in fact Sunday.
Not sure what else to try.

>Solution :

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

It returns True if either day_of_week != "Saturday" or day_of_week != "Sunday" is True.

Which means, if the day is Sunday, day_of_week != "Saturday" still return True and so the total output is still True

You need to replace the or with 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")

Leave a Reply