Calculate remaining days left

how to use value template or any other template that have this function to calculate remaining days left? I have electric billing cycle that bill on every 20th of the month. I need to have one sensor to calculate the day left before the billing cycle start on each month.

I have few scenario below,

  1. let said today is 12th then day left should be 20-12= 8 days
  2. let said today is 28th(provided that month have 31 days) then day left should be (31-28)+20=23days
  3. let said today is 21th(provided that month have 30 days) the day left should be (30-21)+20=29days
  4. let said today is 25th(provided that month have 28days) the day left should be (28-25)+20=23days

as some month have 30, some have 31, Feb might have 28 or 29days. How to compensate for that total of day in the month. The current day should need to be detect by the sensor so that it can auto calculate the remaining days left.

I don’t have time to give you a complete answer but I believe the hardest part is the number of days in the current month?

That can be solved like this:

{% set d = now().replace(day=28) + timedelta(days=4) %}
{{ (d - timedelta(days = d.day)).day }}

You know there has to be at least 28 days, and if you skip forward four days then you are in the next month.
So remove n days from this date and you arrive back on the last day of this month.

The rest of the calculation is just if now().day is more or less than 20 and that is a rather easy if else.

1 Like

@Hellis81 I not really understand the python code, but if I paste your code into the HA template, the result come out is 30?

If your code is based on current date, the result is incorrect, my date here now is 12th, the result should be 8.

remark:
did you mean your code is calculate the total days of current month?

I have no access to my system so cannot check but I remember a script in the HACS script section that does that

Yes

But the full code should probably be something like:

{% if now().day >= 20 %}
{% set d = now().replace(day=28) + timedelta(days=4) %}
{{ (d - timedelta(days = d.day)).day - now().day + 20 }}
{% else %}
{{ 20- now().day }}
{% endif %}
1 Like
{% set x = 1 if now().day >= 20 else 0 %}
{{ (today_at().replace(month= now().month + x,
day = 20) - today_at()).days }}
2 Likes

@Hellis81 @Didgeridrew Thanks for your code, you save my days.

Hi, this formula seem to be not working on December, now the sensor become “unavailable”

I change to this seem to be ok.