How can I calculate network hashrate for a given range of blocks where difficulty changes somewhere within the range? Not sure if the title is poorly worded, but here's what I'm looking to do.

If I have a range of blocks and I want to calculate the hashrate, I can do something similar to what is found here.

To take it a step further, I'd like to be able to calculate hashrate for a given number of blocks from the current block. Using the example provided above, this is rather trivial.

However, I'm running into issues doing this when the difficulty changes somewhere within the range of blocks.

Take last night as an example. Difficulty changed to roughly ~390M. Prior to that it was roughly ~267M. 

How would I go about calculating an average network hashrate for a given range where the difficulty has changed within that range?

Thank you for the help!
Start by computing the total amount of work. Work is defined as the expected number of hashes that were necessary for a particular block. If a block's target is Target, its amount of work is Work = 2**256 / (Target + 1) (follows from the fact that Target + 1 in 2**256 hashes have a value lower or equal to Target). As the difficulty Diff is defined as MaxTarget / Target with MaxTarget = 65535 * 2**208, it follows that Work = Diff * 2**48 / 65535 = Diff * 4295032833.

So, for each block, look at its difficulty, and compute Diff * 4295032833. Compute the sum of all those values for all blocks in your time range.

Now divide that sum-work by the number of seconds your interval lasted. The result is your average number of hashes per second during that interval.

For very short intervals (less than a few hours), it is possible for block timestamp inaccuracy to be relevant. One way to avoid this problem is by starting off not with a range of blocks, but a range of timestamps, and choosing all blocks within that range, rather than estimating the time range from the range blocks.