I tried to create a ‘quit smoking’ template and it works, but I think I can combine the two sensors codes into one code. Only I don’t know exactly how to do it.
My code:
> template:
> - trigger:
> - platform: time_pattern
> # This will update every minute
> minutes: '/1'
> sensor:
> # Keep track how much money I saved since I quit smoking
> - name: Not Smoking Money Saved
> state: >
> {% set smoking_variables_json = {
> "quitdate": "18.09.2021 00:00",
> "priceperday": "9.00" | float,
> } %}
> {{ '€ %.2f'|format(( ( as_timestamp(now()) - as_timestamp(strptime(smoking_variables_json.quitdate, "%d.%m.%Y %H:%M")) ) / 60 * (smoking_variables_json.priceperday / 24 / 60))) }}
>
> # Keep track how many days since I quit smoking
> - name: Not Smoking Days
> state: >
> {% set smoking_variables_json = {
> "quitdate": "18.09.2021 00:00",
> "priceperday": "9.00" | float,
> } %}
> {{ ( ( as_timestamp(now()) - as_timestamp(strptime(smoking_variables_json.quitdate, "%d.%m.%Y %H:%M")) ) / 86400 ) | round }}
For this application, there’s no need to use a Trigger-based Template Sensor with a Time Pattern Trigger. The template contains now() which will cause it to be evaluated every minute in a Template Sensor (i.e. without a 1-minute Time Pattern Trigger).
If you want to combine the two, make the second one report its value as an attribute of the Template Sensor.
If you change the date’s format to something closer to the ISO standard, you can simplify the template even more (because you won’t need to use strptime).
variable:
quit_smoking_quit_date:
value: "2021-09-20 00:00"
quit_smoking_price_per_day:
value: "9.00"
template:
- sensor:
# Keep track how much money I saved since I quit smoking and how many days I didn't smoke
- name: Quit Smoking
icon: mdi:smoking-off
state: >
{{ states('variable.quit_smoking_quit_date') }}
attributes:
quit_days: >
{{ (now() - as_datetime(states('variable.quit_smoking_quit_date'))|as_local).days }}
money_saved: >
{{ '€ %.2f'|format(((now() - as_datetime(states('variable.quit_smoking_quit_date'))|as_local).total_seconds() / 60 * (states('variable.quit_smoking_price_per_day')|float / 24 / 60))) }}