[SOLVED]Time/Date conversion help

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

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

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:

 - platform: template
        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

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'))

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)}}

See if this thread will help you out some:

1 Like

I have this thread bookmarked and visit it sometimes, but i get overwhelmed and confused when i try to do something more complicated :smiley:

Thanks again.

That’s missing the substraction tho right?
It should be something like now()- your code no?

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.