Calculate difference in time in seconds between 2 input_datetime-entities

I have 2 input_datetime-entities with time AND date.
Date is (also) important I think because I want to be able to calculate the difference in seconds between two moments in time, where 1 moment can be before midnight, and the otherone after midnight.

I want to store the difference in an input_number.

My action looks like this, but is not working, what am I doing wrong ?

      - action: input_number.set_value
        data_template:
          value: "{{ states['input_datetime.watermeter_timestamp_nu'].state - states['input_datetime.watermeter_timestamp_vorige'].state }}"
        target:
          entity_id: input_number.watermeter_timestamp_verschil

I believe you would do this for the value

value: "{{ states('input_datetime.watermeter_timestamp_nu') |as_timestamp - states('input_datetime.watermeter_timestamp_vorige')|as_timestamp }}"

State is always a string. If you put this in the template tester in developer tools it will tell you that. Use | as_datetime to convert it to the proper type. Then you’ll see the difference of two as_datetimes is a timedelta. that has a method total_second() to get the seconds:

{{ (states['input_datetime.watermeter_timestamp_nu'].state | as_datetime - states['input_datetime.watermeter_timestamp_vorige'].state | as_datetime).total_seconds() }}

Timedeltas themselves display nicely if you want to use them in the UI.

May I ask what you are intending to use the seconds for? I get the feeling you are trying to do something that Home Assistant has helpers for.

@AllHailJ
I get this error:
ValueError: Template error: as_timestamp got invalid input ‘10:38:49’ when rendering template ‘value: “{{ states(‘input_datetime.watermeter_timestamp_nu’) |as_timestamp - states(‘input_datetime.watermeter_timestamp_vorige’)|as_timestamp }}”’ but no default was specified

@Edwin_D
I get this error: TypeError: unsupported operand type(s) for -: ‘NoneType’ and ‘NoneType’

My watermeter has a reed-contact attached to it. Every 0.5 liter a sensor is updated with the exact amount of water that is used.

I want to use an automation that triggers on every statechange of this sensor.
action 1: copy the current timestampt to the entity that’s holding the previous timestamp
action 2: set the current timestamp to ‘now’
action 3: calculate the difference between the current and the previous timestamp in seconds
action 4: calculate what the water usage would have been per minute when running the water for a longer time:

Steps 1 and 2 are working, step 3 is failing (see errors), step 4 is what I’ll write when step 3 is functioning in developper-tools.

Both input_datetime.watermeter_timestamp_nu and input_datetime.watermeter_timestamp_vorige do have a value stored
(see screenshot)

3 seconds between 2 pulses gives:
60 / 3 * 0.5 = 10 liter/minute

Since my installation does not allow me to consume more than 12 liters/minute, what would give 2.5 seconds between each pulse, I’m more than happy with a rounded accuracy of 1 second (round(0) for 2.5 seconds equals 3, and this gives me 10 liters/minute. The longer the time between 2 pulses the more accurate the reading is.
Starting the second pulse after opening the water faucet I get accurate measures, because when not using water for a long time, it’s possible that there are 100’s or 1000’s of seconds between the first 2 measurements.

Updated 40 minutes after inital message:

I found my mistake. I forgot to reload the input_datetime entities, to reflect the change from has_date false, to true.

Now I’m struggeling with another issue.
When I stop using water, the timedelta remains 4 seconds in this example. So virtually the water keeps running.

- action: input_number.set_value
  data_template:
    value: "{{ 60 / states('input_number.watermeter_timestamp_verschil') | round(0) * 0.5 }}"
  target:
    entity_id: input_number.watermeter_verbruik

This means there was no state for the entities you provided. Where the id names correct and the date time set for both entities? Try to build the template step by step in developer tools. First output just the states of both sensors, if that looks right, convert them to datetime, if that looks right subtract.

You’re trying to convert total water to water per timeunit. That is hard to do right, The sensor to do these calculations is called derivative. It does exactly what you are trying to do. So using that would work better than trying to do it yourself. The derivative result can then be used to extrapolate to longer periods of time.

Note that if the watermeter does not give frequent updates, neither your method or the derivative will work very well. A simple heuristic, based on past experience, measured over multiple runs, might work way better.