How can I convert this string to datetime?

I just installed the Home Assistant Baby Buddy integration. In one of my dashboards, I’d like to reference the sensor.[babyName]_last_change entity to display a line of text like “Last changed X hours ago”.

If I call {{ states('sensor.[babyName]_last_change') }}, I get a string in this format: 2023-02-02T21:59:00+00:00.

I thought I might need to use strptime to parse the string into a datetime object, but when I look at this documentation for strptime, I can’t seem to figure out what directives to use to account for every bit of the resulting string. For instance, I can account for the 2023-02-02 fairly easily, but I don’t understand the T that follows it, nor can I figure out how to account for the time zone offset in +00:00 format.

I’m also still very wet behind the ears when it comes to templating, so I might be doing this the very hard way. If you have any tips on how I could more easily take the string output of sensor.[babyName]_last_change and produce text like “Last changed X hours ago,” I’m all ears!

Try this in the Developer Tools Template Editor:

{{ states('sensor.[babyName]_last_change')|as_datetime|relative_time }}

2 Likes

That did the trick, thank you.

1 Like