Number of Calendar Days Since 'X'

Hey all, so I want to set a sensor template to display the number of days since I did a workout… trying to give myself some additional motivation! :laughing:

I have the below working, however it doesn’t work quite right. I want to say how many calendar days since my workout, so for example if I work out at 6pm today, it should show “0” days for the rest of the day, and then after midnight it should show “1” day, after midnight the next day “2” days etc

However, using the above example, it will not show “1” day until 6pm the next day.

      days_since_workout:
          friendly_name: Days Since Workout
          value_template: "{{((as_timestamp(now()) - as_timestamp(states('sensor.on_peloton_end_time'))) / 86400) | int }}"

I understand why this is happening (because thats when the duration goes over 24hours), but can’t work out how to make it work how I want it to.

I suspect I need to change the as_timestamp(now()) statement, to be configured to something like 23:59:59 of ‘today’, rather than the current time… though am sure someone probably has a better solution!

Any help would be great… I know this will be simple and will have been done many times, but I’m going in circles at the moment and my searches on here and google are coming up blank.

Thanks!

One method is to compare like times (usually midnight is easiest). There are a bunch of different ways to do that… here are two options:

{% set last = states('sensor.on_peloton_end_time')[:10]%}
{{ (today_at() - last | as_datetime | as_local).days }}
{% set last = (states('sensor.on_peloton_end_time')
| as_datetime | as_local).replace(hour=0, minute=0, second=0) %}
{{((as_timestamp(today_at()) - as_timestamp(last)) / 86400) | int }}
4 Likes

Thanks @Didgeridrew

That’s perfect, have used the first example as it was more concise and it works great, though I can see how the second one would work too.

Quick query for my understanding, What does the [:10] in the first example do?

Thanks again!

In Home Assistant states are strings so you so you can use string indexing and slicing to extract individual letters, words, etc. So, [:10] takes the datetime string from your sensor’s state i.e. 2022-10-30 21:55:44 and returns the first 10 characters, 2022-10-30.

1 Like

Thanks, that’s great to know, and makes full sense… I always like to understand and learn when you guys help me out!