Convert timestamp to time - string

I have got a timestamp string attribute:
this_sp_from: '2023-02-19T22:00:00+01:00'

that I would like to convert to a TIME-string

22:00

I have tried using the templating documentation with the strptime() filter with the formatcode %X and %H:%M but the template returns an error

{{states.climate.slaapkamer_achter.attributes["status"].setpoints.this_sp_from}}

returns the timestamp string: 2023-02-19T22:00:00+01:00

 {{strptime(states.climate.slaapkamer_achter.attributes["status"].setpoints.this_sp_from,%X)}}

returns: TemplateSyntaxError: unexpected ‘%’

What am I doing wrong?

Take advantage of python’s ability to easily slice strings.

{{ states.climate.slaapkamer_achter.attributes["status"].setpoints.this_sp_from[11:-9] }}
1 Like

try this:

{{as_timestamp(strptime(states.climate.slaapkamer_achter.attributes["status"].setpoints.this_sp_from, '%Y-%m-%dT%H:%M:%S%z'))|timestamp_custom('%H:%M')}}
1 Like

Thank you, works fine. And I learned st about Python!

Thank you works fine. I will pick this solution, since it offers me the most flexible options to get what ever I want in 1 string.

Pitty though that I don’t fully understand why it works this way. It feels like doing it twice. I’ll dive into that to learn why.

I mean, it kind of is but it’s process.

you need to convert the string of numbers and letters into a valid datetime object which is what strptime does. Then you need to extract the hour and minute data out of the datetime object which is what the rest is doing.

or you can just extract the data you want out of the string itself using python string manipulation methods as 123 suggested. Which will work just fine as long as the string you are manipulating is alwaqys in the same format.

you can look here for more info on how datetimes work. I’ve been told it’s fairly helpful. :wink:

1 Like

Thank you! Very good epic!

1 Like

What other options do you require to extract the time out of the datetime string?

There are at least two conversions involved. It converts the datetime string to a datetime object then to a timestamp and then to a time string.

If you wish, you can eliminate the step involving conversion to a datetime object:

{{ states.climate.slaapkamer_achter.attributes['status'].setpoints.this_sp_from | as_timestamp | timestamp_custom('%H:%M') }}
1 Like

This one looks nice and 'onsistant to me! Thank you!