Adding Hours to a Time

Hi all,

I have an attribute from a rest sensor that currently stores a string with the latest tide value (Imperfect, I know).

I’m trying to get 2 values, 1 hour each side of high tide.

The sensor looks like this:

And is populated from this in my config.yaml sensor sub file:

Right now I’ve got the following, but need to add and subtract 1 hour from the time attribute to display on my dashboard.

I’ve tried multiple ways to add seconds, or use timedelta( hours = 1 ), but cannot get it to work. It keeps complaining that I am trying to add something (i.e. a timedelta or an int) to a string so I presume I need to convert the attribute value to something first but can’t work out how to do it.

Bonus points if this can be done before the value is put into the attribute (e.g. in the sensors config) if that makes it cleaner.

{% if is_state_attr('sensor.tide_date_1_values_1', 'type', 'high') %}
{{ as_timestamp(strptime(state_attr('sensor.tide_date_1_values_1', 'time')|replace(" ",""), '%H:%M%p')) | timestamp_custom('%-I:%M %p') }}
{% endif %}

If you want to modify the data

don’t do it as an attribute, set it up as an independent sensor.

      - name: Tide First High Tide Time Range
        value_template: |
          {% set tide_obj = value_json.locations[0].days[0] %}
          {% set time = (tide_obj.tides | selectattr('type', 'eq', 'high')
          |map(attribute='timestamp')|list)[0]|as_datetime|as_local %}
          {{(time - timedelta(hours=1)).strftime("%-I:%M")}}-{{(time + timedelta(hours=1)).strftime("%-I:%M%p")}}
      - name: Tide Second High Tide Time Range
        value_template: |
          {% set tide_obj = value_json.locations[0].days[0] %}
          {% set times = (tide_obj.tides | selectattr('type', 'eq', 'high')
          |map(attribute='timestamp')|list) %}
          {% if times|count > 1 %}
          {% set time = times[1]|as_datetime|as_local %}
          {{(time - timedelta(hours=1)).strftime("%-I:%M")}}-{{(time + timedelta(hours=1)).strftime("%-I:%M%p")}}
          {% else %} No Second High Tide Today {% endif %}

i dunno the tradeoffs you’re making and whether it’s better or not to create a separate sensor or not… but to answer your question on how to convert your “4:01AM” to add/remove an hour…

{{ (strptime("04:05PM", "%I:%M%p") - timedelta(hours=1)).time()}}