Calculating kWh from instantaneous W

Hello, I had similar problem and based on emoncms source code I done own solution: https://github.com/emoncms/emoncms/blob/master/Modules/input/process_model.php (functions power_to_kwh and power_to_kwhd) I done custom SQL query to database.
I avoided putting mathematic logic to OpenHAB - for me OpenHAB is only presentation and automation layer.

My scenarion looks like below:

[energy meter/arduino] --mqtt--> [broker] --mqtt--> [mqtt2zabbix] --zabbixAPI--> [zabbix server] --SQL--> [custom script] --mqtt--> [broker] --mqtt--> [OpenHAB]

The path is so long because zabbix was first. I have plan to use OpenHAB mysql persistance instead of zabbix. So my path will be like this:

[energy meter/arduino] --mqtt--> [broker] --mqtt--> [OpenHAB persistance] --SQL--> [custom script] --mqtt--> [broker] --mqtt--> [OpenHAB]

Here my query for today usage since 00:00 (postgresql):

select sum(value)*( ( extract(epoch from now()) - extract(epoch from current_date) ) /count(value))/3600/1000 as sincemidnight from history where itemid=24427 and clock between extract(epoch from current_date) and extract(epoch from now());