There are many ways to accomplish this. Mechanical demand meters use a different technique than do electronic meters. Utilities use a different algorithm than do most power management devices (sliding window, fixed interval etc.)

The underlying concept is to decide on a number of sampling intervals per demand interval. At the end of each sampling interval add the new KW reading to the total KW of the previous intervals. At the end of the demand interval, divide the total KW by the number of sampling intervals.