Perform "math/SUM" operator on time value on history_stats

Hi all,

I have created multiple history stats to monitor the time I am in each state in teams using following example:

  - platform: history_stats
    name: Teams Stat Activity In A Conference Call
    entity_id: input_select.microsoft_teams_activity
    state: "In A Conference Call"
    type: time
    start: "{{ now().replace(hour=0, minute=0, second=0) }}"
    end: "{{ now() }}"

  - platform: history_stats
    name: Teams Stat Activity In A Meeting
    entity_id: input_select.microsoft_teams_activity
    state: "In A Meeting"
    type: time
    start: "{{ now().replace(hour=0, minute=0, second=0) }}"
    end: "{{ now() }}"

I would like to have also a sensor for the SUM of different states, for which I used the below solution:

  - platform: template
    sensors:
      work_time_today:
        friendly_name: "Teams Work Time"
        icon_template: mdi:microsoft-teams
        value_template: "{{ (states('sensor.teams_stat_activity_in_a_call')|float(2)  + states('sensor.teams_stat_activity_in_a_conference_call')|float(2)  +states('sensor.teams_stat_activity_available')|float(2)  +states('sensor.teams_stat_activity_idle')|float(2))| round(2)  }}"
    

However, this does not provide the same nice format as the history_stat, namely the attribute:

Result of SUM (without time format):

Attribute Iā€™m looking forward:

Does anyone suggest a way forward? It would be nice is history_stat supported multiple states.

Convert the hours into seconds and then use the timestamp_custom filter.

  - platform: template
    sensors:
      work_time_today:
        friendly_name: "Teams Work Time"
        icon_template: mdi:microsoft-teams
        value_template: >
          {{ ((states('sensor.teams_stat_activity_in_a_call')|float(2)  + 
               states('sensor.teams_stat_activity_in_a_conference_call')|float(2) +
               states('sensor.teams_stat_activity_available')|float(2) + 
               states('sensor.teams_stat_activity_idle')|float(2)) * 3600)
             | timestamp_custom('%-Hh %-Mm', false, 0) }}

Thank you very much!

1 Like

I was looking for this as well.

I calculated the sum in seconds. then converted it to a timedelta object (see Templating - Home Assistant)

this displays the value as time without converting it to a string as timestamp_custom does.