krash
(Harry)
May 19, 2021, 7:29am
1
Hey everyone,
This is probably a stupid question but I can’t make it work.
I have a sensor reporting its last_update
in this format: last_update: 19-05-2021 10:23
I am trying to convert it to timestamp / unix time to do some calculations but the as_timestamp()
function gives me a blank result.
How should i try working with it?
Is the timestamp_custom
function to be used here? and if so how?
Thanks in advance.
1 Like
Hellis81
(Hellis81)
May 19, 2021, 7:46am
2
This should work…
{% set t = "19-05-2021 10:23" %} # sensor attribute
{{ as_timestamp(t[6:10] ~ "-" ~ t[3:5] ~ "-" ~ t[0:2] ~ t[10:16]) }}
1 Like
krash
(Harry)
May 19, 2021, 10:16am
3
Thank you, that did the job.
Here is my final code where i count the minutes since the last update, in case somebody sees it in the future:
sensor:
- platform: template
sensors:
time_since_last_update:
friendly_name: "random sensor updated"
value_template: >
{% set t = states.sensor.randomsensor.attributes['last_update'] %}
{{((as_timestamp(now()) - as_timestamp(t[6:10] ~ "-" ~ t[3:5] ~ "-" ~ t[0:2] ~ t[10:16]) )/60)|round(0)}}
unit_of_measurement: "Minutes"
icon_template: mdi:timer
finity
May 19, 2021, 10:38am
4
Or you could use the strptime function to convert the string to a datetime and then use the as_timestamp function it:
as_timestamp(strptime(states.sensor.randomsensor.attributes['last_update'], '%d-%m-%Y %H:%M'))
krash
(Harry)
May 19, 2021, 10:53am
5
Thank you.
This works great too. (Just outputs seconds, so i had to devide by 60)
{{(((as_timestamp(now()) - as_timestamp(strptime(states.sensor.randomsensor.attributes['last_update'], '%d-%m-%Y %H:%M'))))/60)|round(0)}}
finity
May 19, 2021, 10:58am
6
See if this thread will help you out some:
After seeing many threads on the forum asking for help with time conversions and calculations using time and realizing I generally had no real understanding of how time worked in HA I decided to dig in and try to figure it out.
After over a week of internet and forum searches I think I’ve now got a lot of it figured out. I’m sure there is more that I don’t have here because sometimes “you don’t know what you don’t know”.
So, since I didn’t know this stuff and because of the number of other pos…
1 Like
krash
(Harry)
May 19, 2021, 11:11am
7
I have this thread bookmarked and visit it sometimes, but i get overwhelmed and confused when i try to do something more complicated
Thanks again.
krash
(Harry)
May 19, 2021, 12:04pm
9
123:
value_template: "{{ strptime(state_attr('sensor.randomsensor', 'last_update'), '%d-%m-%Y %H:%M').timestamp() / 60 | int }}"
That’s missing the substraction tho right?
It should be something like now()- your code
no?
123
(Taras)
May 19, 2021, 12:21pm
10
You are correct; I forgot to include it. However, adding now().timestamp()
to perform a subtraction requires the addition of nested parentheses which results in a messy template. It’s not worth a second look so I deleted my post.