(solved) Template to convert string to date or time, with timezone conversion?

Hi, I am trying to show on HA the turn-on and turn-off hours of a light.
This time comes from node-red in json format, sent via mqtt. This is the output in node-red debug window:

info : msg.payload : Object
object
on: "Fri, 17 Aug 2018 18:48:31 GMT"
off: "Fri, 17 Aug 2018 21:43:39 GMT"
state: "off"

In HA I have created two mqtt sensors, where I extract the on and off times from the mqtt topic.
Here I see that the date and time is in GMT format, and I’d like to extract only the time and convert it to my timezone (GMT+2 in summer, GMT+1 in winter)
This is the off time as seen in HA:

Fri, 17 Aug 2018 21:43:39 GMT

I have tried several templates but I haven’t been able to do this conversion easily (taking into account the summer/winter time)

With this one I have been able to get the time and the timezone:

{% set strtext = states.sensor.timer1_off.state %}
{% set strtext2 = strtext.split(’ ‘)[4]+’ ‘+strtext.split(’ ')[5] %}
{{strtext}}
{{strtext2}}

Wich gives as result:

Fri, 17 Aug 2018 21:43:39 GMT
21:43:39 GMT

Using as_timestamp(), timestamp_local and others only returned empty strings or the same string

Any help?

{% set strtext = states.sensor.timer1_off.state.replace(' GMT','+0000') %}
{{ strptime(strtext, '%a, %d %b %Y %H:%M:%S%z') }}
3 Likes

Thank you!

After trying the solution extensely, the templated time is still showing in the original GMT:

Data from mqtt sensor after substituting ’ GMT’ with ‘+0000’ {{strtext}}:

Sat, 18 Aug 2018 18:49:19+0000

Result with the template:

2018-08-18 18:49:19+00:00

So this time is not in my local time. I think I’m there but already stuck.

The result of the template is indeed a timezone aware datetime object in UTC. But you can easily convert it to your local timezone. E.g.:

{% set strtext = states.sensor.timer1_off.state.replace(' GMT','+0000') %}
{{ strptime(strtext, '%a, %d %b %Y %H:%M:%S%z').timestamp()|timestamp_local }}

If you don’t like the format of timestamp_local, you can always use timestamp_custom and supply your own format string.

1 Like

I was missing the .timestamp() part.

Thank you for the quick reply. Works like a charm!

1 Like

Holy cow, I can’t believe how much time I spent figuring this out! Every other post seems to indicate strptime simply discards the timezone information, but using “%z” and “+0000” works like a charm.

Thanks!