Parse UTC time and display local time (with DST)

I would like to extract the UTC timestamp from the following MQTT message and display it as local time:

	"temps": [38.0625, 69.8125, 37.8125, 69.875],
	"NTC": 39.41295624,
	"RSSI": 166,
	"dBm": -90,
	"LoRa status": "Success",
	"timestamp": "14:47:31"
{{ strptime(value_json["timestamp"], '%H:%M:%S') }}

Parses the timestring but I suspect it sets the date to 01/01/1970 and because of it the UTC to local conversion doesn’t quite work.

Any help would be much appreciated.

{{ strptime(utcnow().date()~value_json['timestamp']~'-00:00', '%Y-%m-%d%H:%M:%S%z') | as_local }}

1 Like

Several ways to convert it; here’s another:

{% set (h,m,s) = value_json['timestamp'].split(':') | map('int',0) %}
{{ utcnow().replace(hour=h, minute=m, second=s, microsecond=0) | as_local }}

Yet another; this one is similar to the approach employed by Didgeridrew but uses as_datetime instead of strptime to convert the datetime string to a datetime object.

{{ '{}T{}+00:00'.format(utcnow().date(), value_json['timestamp']) | as_datetime | as_local }}
1 Like

Thank you guys. Both your solutions worked but the formatting looked kind of wonky:
2023-08-04 11:49:11+02:00
Not really easy to read with the timezone adjustment value at the end so I improved it a bit.

I ended up converting the datetime object to UNIX timestamp and using a filter to display HH:MM:SS only.

{% set (h,m,s) = value_json['timestamp'].split(':') | map('int',0) %}
{{ as_timestamp(utcnow().replace(hour=h, minute=m, second=s, microsecond=0)) | timestamp_custom("%H:%M:%S", local=True) }}

Thank you again for your help, I learned a lot.

You marked your own post with the Solution tag, despite the fact it contains information provided by others. The custom of this community forum is to assign the tag to the first post whose suggestions are used to solve your original problem. 99% of the template in your post came from this post.

If every user marked their own post as the Solution, it would give the impression that everyone ultimately solves their own problems.

FAQ Guideline 21

I wasn’t aware of this rule, thanks for letting me know.

1 Like