Number of days in a month

My energy provider is charging me a fee every month and I would like to divide this charge through the amount of days that month.

The general idea is to use Python’s monthrange:

- platform: template
  sensors:
    daily_cost_electrics:
      friendly_name: Daily cost of electrics
      value_template: >
        {% set e = states('sensor.monthly_cost_electrics') %}
        {% set y = now().strftime('%Y') %}
        {% set m = now().strftime('%m') %}
        {% r = monthrange(y, m) %}
        {{ e / r | float(0) | round(2) }}

How can I solve this or what is my best approach?

Not all Python methods are available for use in templates.

- platform: template
  sensors:
    daily_cost_electrics:
      friendly_name: Daily cost of electrics
      value_template: >
        {% set e = states('sensor.monthly_cost_electrics') | float(0) %}
        {% set r = ((now().replace(day=1) + timedelta(days=31)).replace(day=1) -timedelta(days=1)).day %} %}
        {{ (e / r ) | round(2) }}

Correct me if I am wrong but the formula that computes the variable r only works properly for months with 31 days.

If I force the template to use a date in September (a month with 30 days), it reports 1. If I choose a date in February, it reports 3.

{{ (as_datetime('2022-09-14').replace(day=1) + timedelta(days=31) - timedelta(days=1)).day }}

I believe this is what you want:

{% set r = 31 if now().month == 12 else (now().replace(month=now().month+1, day=1) - timedelta(days=1)).day %}

Basically, it’s the template from the following post which was used to get the last day of a month.

2 Likes

@123 you’re missing the second replace()

I tested it and it works for all months… including Dec. and leap year Feb.

But your example is more compact…

1 Like

I just use this as the multiplier. It’s easy and works with everything. No need to work out how many days :slight_smile:

now().day
2 Likes

I’m going to use this sensor in the Energy dashboard and it will allow me to spread the fixed cost of energy evenly throughout the month. With your “trick” I would pay the whole fixed cost on the first day, then again half on the second day, a thrid on the third day, etc. etc. @123 has provided a great sollution to solve my issue.

Ah - no worries. Mine is a daily rate which explains why my “trick” works :slight_smile: