Timestamp convertion + time difference

I’m very new to Home Assistant and I’m trying to convert a time which I get from a Rest platform.
In the value_template I have this string “7:12:14 PM” and I wanted first to convert it into 24-format

I then created a template platform to convert the value stored in the Rest sensor into the format I’m looking for.

  value_template: >
    {{ as_timestamp(states.sensor.rest_time.state) | timestamp_custom(' %H:%M:%S ') }}

But this returns “None” while I did expect 19:12:14

Secondly, I want to have another time loaded in another sensor and I would like to calculate the time difference between 2 sensors:

e.g.

Sensor1: 19:12:14
Sensor2: 18:07:08

Calculation: 01:05:06

Any suggestion on how to manage at best these 2 conditions?

Thanks a lot in advance!

The UNIX timestamp is “seconds since the beginning of 1 Jan 1970”. The time value you’re trying to convert is being interpreted as 7PM on 1 Jan 1900, which isn’t a valid timestamp. Try this:

{{ strptime("2000-01-01 " + states.sensor.rest_time.state, "%Y-%m-%d %I:%M:%S %p")|as_timestamp|timestamp_custom("%H:%M:%S") }}

which fakes it into being a time on 1 Jan 2000 instead. It does seem like a lot of hoops to jump through — hopefully someone will suggest something better…

For the second part — once you have working timestamps (as above without the timestamp_custom bit), you can just subtract them then do the timestamp_custom, making sure that what you pass it is a positive number.

Thank you - solved like a charm the first part, while I’m a bit struggling with the second one.
Assuming I have the 2 following timestamps

[sensor.time_today_timestp] 946694664.0
[sensor.time_yesterday_timestp] 946694616.0

is the following approach correct?

  value_template: >
    {{ states.sensor.time_today_timestp.state - states.sensor.time_yesterday_timestp.state }}

Thanks again!

You need to convert the states to floats (jinja/template verbiage that means decimal number) to perform math.

  value_template: >
    {{ states.sensor.time_today_timestp.state | float  - states.sensor.time_yesterday_timestp.state | float }}

I also recommend using the state method instead of the state object. It will produce less errors during startup.

  value_template: >
    {{ states('sensor.time_today_timestp') | float - states('sensor.time_yesterday_timestp') | float }}
1 Like

Thanks a lot - this worked perfectly!

Hi! I tried this in my automation with two times from two helpers (input_datetime.time1 and .time2).
but it doesn’t work…
Which action is necessary?
like this:

action:
and then??

Thank you!!