Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading