Yes you can! With pandas_market_calendars
. See: GitHub - Repo. From the docs
import pandas_market_calendars as mcal
nyse = mcal.get_calendar('NYSE')
schedule = nyse.schedule(start_date='2016-12-30', end_date='2017-01-10')
market_open market_close
2016-12-30 2016-12-30 14:30:00+00:00 2016-12-30 21:00:00+00:00
2017-01-03 2017-01-03 14:30:00+00:00 2017-01-03 21:00:00+00:00
2017-01-04 2017-01-04 14:30:00+00:00 2017-01-04 21:00:00+00:00
2017-01-05 2017-01-05 14:30:00+00:00 2017-01-05 21:00:00+00:00
2017-01-06 2017-01-06 14:30:00+00:00 2017-01-06 21:00:00+00:00
2017-01-09 2017-01-09 14:30:00+00:00 2017-01-09 21:00:00+00:00
2017-01-10 2017-01-10 14:30:00+00:00 2017-01-10 21:00:00+00:00
For your starting timestamp, you can calculate the difference until the end of the 1st trading day.
For your ending timestamp, you can calculate the difference from the start of the last trading day.
For the rest of the days, the time to accumulate is obviously the ending time minus the starting time. Even if the output above has the same starting/ending times, it will not always be the case as in:
early = nyse.schedule(start_date='2012-07-01', end_date='2012-07-10')
market_open market_close
2012-07-02 2012-07-02 13:30:00+00:00 2012-07-02 20:00:00+00:00
2012-07-03 2012-07-03 13:30:00+00:00 2012-07-03 17:00:00+00:00
2012-07-05 2012-07-05 13:30:00+00:00 2012-07-05 20:00:00+00:00
2012-07-06 2012-07-06 13:30:00+00:00 2012-07-06 20:00:00+00:00
2012-07-09 2012-07-09 13:30:00+00:00 2012-07-09 20:00:00+00:00
2012-07-10 2012-07-10 13:30:00+00:00 2012-07-10 20:00:00+00:00
So you actually need to iterate over the results and calculate the accumulated time for each trading day.
Of course: your instrument has to be in one of the supported calendars (or else you can create your own)