Found this thread - it looks its still an issue to find exactly last day of a month.
I created a template sensor:
last_day_of_month:
value_template: >-
{{
31 if now().month in (1,3,5,7,8,10,12) else
30 if now().month in (4,6,9,11) else
29 if now().month == 2 and now().year % 4 == 0 else 28
}}
Like tom_I said, it was solved in post #6 a year ago.
A year is a long time in Home Assistant’s evolution. Here is the same binary_sensor but in the new ‘modern’ format with a refactored template that takes advantage of the timedelta function.
# Last Day of the Month Binary Sensor
template:
- binary_sensor:
- name: Last Day of the Month
icon: mdi:calendar
state: "{{ (now() + timedelta(days=1)).day == 1 }}"
Works over year boundaries, and provided the time libraries are maintained, will cope with the change I’ll put in when I’m King that leap years are every four, except when the year divides by 128, which makes for much quicker computation (convert to binary, leap if ends in 00, except if ends in 0000000).
Gets the first of the current month, adds 32 days to get into the next month, gets the first of that month, subtracts a day and returns the date number.
The original goal of this topic was to trigger on the last day of the month. It amounts to knowing if the current day is or is not the last day. True/False is sufficient to trigger the automation and so that’s why it’s a Template Binary Sensor.
However, if there is a need for a Template Sensor to report the numeric value of the month’s final day, here’s something I adapted from the python code in this post:
# Last Day of the Month Sensor
template:
- sensor:
- name: Last Day of the Month
icon: mdi:calendar
state: "{{ 31 if now().month == 12 else (now().replace(month=now().month+1, day=1) - timedelta(days=1)).day }}"
I think I found a way. Maybe not the best but I get the value that I want. My goal is to use the template value to start and end the calculation of a average value. Is it possible to add a fixed time after the date? Like I have done below.
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 548, in async_update_ha_state
await self.async_device_update()
File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 746, in async_device_update
raise exc
File "/config/custom_components/average/sensor.py", line 290, in async_update
await self._async_update_state()
File "/config/custom_components/average/sensor.py", line 413, in _async_update_state
await self._async_update_period()
File "/config/custom_components/average/sensor.py", line 368, in _async_update_period
if start > now:
TypeError: can't compare offset-naive and offset-aware datetimes
This uses the condition template to determine day of month, and the time pattern to control the time of the day for the triggering. This is slightly easier to check as I can manually fire the automation and check everything except the time trigger.