loovanloon
(Ton van Loon)
February 20, 2023, 12:46am
1
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?
123
(Taras)
February 20, 2023, 1:07am
2
Take advantage of python’s ability to easily slice strings.
{{ states.climate.slaapkamer_achter.attributes["status"].setpoints.this_sp_from[11:-9] }}
1 Like
finity
February 20, 2023, 6:11am
3
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
loovanloon
(Ton van Loon)
February 20, 2023, 7:33am
4
Thank you, works fine. And I learned st about Python!
loovanloon
(Ton van Loon)
February 20, 2023, 7:35am
5
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.
finity
February 20, 2023, 8:43am
6
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.
1 Like
loovanloon
(Ton van Loon)
February 20, 2023, 1:15pm
7
Thank you! Very good epic!
1 Like
123
(Taras)
February 20, 2023, 1:19pm
8
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
loovanloon
(Ton van Loon)
February 21, 2023, 10:49am
9
This one looks nice and 'onsistant to me! Thank you!