Fasting hour counter

Good afternoon,
I have been reading and testing for days on how to make a sensor that counts my daily fasting hours.
I usually stop eating between 4 p.m. and 5 p.m. and eat again at 10 a.m. or 11 a.m. the next day.
The last thing I have tried with an Input boolean and History stats but I can’t reset it or do well that the sensor doesn’t reset at 12pm.
Does anyone have something similar or do they have any idea where to start again?
Thank you very much in advance

This is the last thing I’ve tried.

platform: history_stats 
name: Tiempo Ayunando David
entity_id: input_boolean.ayuno_david
state: 'on' 
type: time 
start: '{{ now().replace(hour=0).replace(minute=0).replace(second=0) }}' 
end: '{{ now() }}'

My idea would be to press a button when I start fasting and press the same one or another when I start eating again and that those hours of fasting (in hh:mm:ss format) are saved in some way that I can send a notification by Telegram to have a “daily” record of how many hours I have fasted.
The problem is that those hours can vary depending on the day
And that fasting hours always take hours of two different days.

One way to do it is to use a pair of template sensors and an input boolean helper that you switch on and off:

template:
  - trigger:
      - platform: state
        entity_id: input_boolean.ayuno_david
        to: 'on'
        from: 'off'
    sensor:
      - name: Started Fasting
        state: "{{ now() }}"
  - sensor:
      - name: Fasting Hours
        state: >
          {% set current = this.state | default(0, true)%} 
          {% if is_state('input_boolean.ayuno_david', 'off') %}
            {{ current }}
          {% else %}
            {{ (( now() - states('sensor.started_fasting') 
            | as_datetime | as_local).total_seconds() / 3600) | round(1) }}
          {% endif %}

There are multiple ways to set this up depending on how you need it to function. As shown above the Fasting Hours sensor will count up as long as the boolean is ‘on’. When it’s turned off, it will maintain the day’s max value until switched on again.

1 Like

Hi Drew.
Thank you very much for responding.
I understand that what I would have to do then is to create those two sensors in the first place to my yaml?

Excuse me, but although I have been with HA for a long time, I have touched on the issue of sensors very little.
To give you more details, the sensors that I have created I have put them all inside a folder inside the config and in configuration.yaml I have indicated

sensor: !Include_dir_list sensors/

I have already created a boolean input_boolean.ayuno_david
that I created yesterday when I did the tests

Yes you would need to paste the sensors into your configuration. As shown, they need to be under the template top-level key. That means they do not go in your sensors directory. They can go directly in your configuration.yaml or you could start a directory for them since that is what you are used to. To do that you would add template: !include_dir_list templates/ to your configuration.yaml and create a folder.

1 Like

Good morning, ok perfect, I’m going to try it and I’ll tell you

I have created the templates like this and I receive the following error code


Invalid config for [template]: [template] is an invalid option for [template]. Check: template->template. (See /config/templates/template_ayuno.yaml, line 1).

The convention used in the docs and that some users continue on these forums, where possible, is to present configuration code as if it is being placed directly in the configuration.yaml file. You are not placing the template sensor configuration directly in configuration.yaml, so yours will not be exactly as I posted above.

I don’t use !include_dir_list, but IIRC you need to put each entry in its own file like:

/config/templates/ayuno_hora_de_inicio.yaml

trigger:
  - platform: state
    entity_id: input_boolean.ayuno_david
    to: 'on'
    from: 'off'
sensor:
  - name: Started Fasting
    device_class: timestamp
    state: "{{ now() }}"

/config/templates/ayuno_duracion.yaml

sensor:
  - name: Fasting Hours
    unit_of_measurement: horas
    state: >
      {% set current = this.state | default(0, true)%} 
      {% if is_state('input_boolean.ayuno_david', 'off') %}
        {{ current }}
      {% else %}
        {{ (( now() - states('sensor.started_fasting') 
        | as_datetime | as_local).total_seconds() / 3600) | round(1) }}
      {% endif %}
1 Like

Ok, as I understand that according to what you tell me, the correct thing is to install the sensors and templates in the way you previously indicated, before bothering you again I will read again and inform myself here about this topic and as soon as I do more tests I will answer you again.

Thank you very much again :grinning:

Good evening again Drew, sorry for the delay but until today I have not been able to calm down with this.
Today I have finally ordered my configuration.yaml and I have added the template as you indicated here, it has worked for me and it has created the two sensors, I pressed the test just before 12pm and when that time arrived it did not work. restarted, I attach screenshot.
The problem is that it shows me the hours like this and I can’t get it to show them in HH:MM:SS format, which is how I would like it to show them to me.

Let’s see if you can think of how I could do so that the hours are seen with this HH:MM:SS format so that at the end of the fast you could send me a message by telegram with those total hours of fasting for that day.
I will continue investigating and doing tests to see if I can do it too.

Thank you very much in advance

Greetings

What has worked perfectly for me is that by turning input_boolean.ayuno_david to Off, the start times and the hours counted by the Fasting Hours sensor have been maintained and by turning input_boolean.ayuno_david back to ON, the hours have started again from scratch :heart_eyes:

There are a couple ways to do formatted durations. Since your case should never go past 24 hours, you can use the simpler method.

sensor:
  - name: Fasting Duration
    state: >
      {% set current = this.state | default(0, true)%} 
      {% if is_state('input_boolean.ayuno_david', 'off') %}
        {{ current }}
      {% else %}
        {% set total_s = (( now() - states('sensor.started_fasting')|as_datetime| as_local).total_seconds()) %}
        {{ ( total_s | as_datetime).strftime('%H:%M:%S') }}
      {% endif %}

I’m going to drive you crazy and I keep thinking about it but it gives me the following error.

No worries, I missed a ) after total_seconds()… I have fixed it in the post above.

:man_facepalming:t2: A simple parenthesis,

I’m sorry I didn’t detect it because I’ve thought about it a lot. Perfect Drew, precisely in a few minutes I am going to start the fast so I have corrected the sensor, it has no longer given me failures and as soon as the fast begins I press it and tomorrow as soon as I finish it I will tell you :crossed_fingers:t2:

Thank you very much again

1 Like

For now, it is marking the times well. I’m going to wait until tomorrow to finish the fast and see how it restarts and while I’m going to see how to make a good graph with the data obtained to at least be able to contribute something to the project.

This last correction seems to be the final one :muscle:t2:

Hello again Drew, how are you?

First of all, thank you again because this is already taking shape.

I’ll tell you and the rest if anyone is interested in what I’ve created so far

1º) I have made a modification to what you sent me to create another sensor and be able to get the beginning of my fast with the format timestamp_custom(’%d/%m/%Y a las %H:%M:%S’)

With that what I have achieved is that it comes out in a more friendly way for me than how it came out just like you sent it to me

I don’t know if it will be possible to directly modify the sensor you created so that two are practically the same. If it can be modified, you will tell me.

On the other hand, I have checked that it works perfectly and that even if HA is restarted, the data is maintained.

This is the notification that I have created once I press the end of my fasting hours.

And this is the card that I initially created. I am also attaching the format that I have given you so that only the hours appear in the LoveLace while I am fasting, the moment I stop fasting the hours that you see in red are hidden.

The only thing I would have left and I would like is to make some kind of bar chart so that in which I can see the hours that I have been fasting for example the last 30 days but so far I have not achieved it because it divides the bars By David Oliveros®  hours.

Likewise, if anyone knows how to solve it, I would appreciate it.

Let’s see what you think about how everything is going.

Thanks a lot