I’m working on my energy dashboard and one of the things I want there is previous month energy usage.
I am using energy meter so I am thinking about using a input number that is then switched to a sensor and using automation that will run at the last day of each month at 23;59 to copy that data (similar to what was achieved here: https://community.home-assistant.io/t/yesterday-energy-consumption-in-esphome/259765/2
How do I tell home assistant to run automation at the last day of each month at 23:59?
Any pointers are greatly appreciated.
Thanks
Time trigger at 23:59 every day.
trigger:
platform: time
at: '23:59'
Template condition to check if tomorrow is the first day of the month.
condition:
- "{{ (now() + timedelta(days=1)).strftime('%d') == 1 }}"
Action: store your value.
Alternatively if you want to skip the input_number intermediary and store the value directly in the sensor you can use the new triggered sensors. You just have to put the condition in the trigger (triggered sensors don’t support conditions).
template:
- trigger:
platform: template
value_template: "{{ now().hour == 23 and now().minute == 59 and (now() + timedelta(days=1)).strftime('%d') == 1 }}"
sensor:
- name: 'Energy Last Month`
unit_of_measurement: 'kWh'
icon: mdi:counter
state: "{{ states('sensor.your_energy_meter') }}"
Just a minor correction.
.strftime('%d') == 1
Should be:
.strftime('%-d') == 1
Took me a while to figure this out, but strftime() returns a string, not an integer. Therefore the correct code should include ‘’ around the value, otherwise it always returns “false”:
"{{ now().hour == 23 and now().minute == 59 and (now() + timedelta(days=1)).strftime('%-d') == '1' }}"
Batts
And a more elegant solution again for the last day of the month component, thanks to @Troon, is
"{{ (now() + timedelta(days=1)).day == 1 }}"
so
"{{ now().hour == 23 and now().minute == 59 and (now() + timedelta(days=1)).day == 1 }}"