The EPIC Time Conversion and Manipulation Thread!

Something’s very wrong with that timestamp value…

This should work, but defaults to 0:

{{ trigger.json.timestamp | timestamp_local(0) }}

Trying it in Python to debug it further, I get this:

In [6]: from datetime import datetime

In [7]: datetime.fromtimestamp(1695210904538)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-7-eee505ea12e4> in <module>
----> 1 datetime.fromtimestamp(1695210904538)

ValueError: year 55689 is out of range

Divide it by 1000, or 100. Sometimes apis use a timestamp in millisecond or microseconds

You’re right!

{{ (1695210904538/1000) | timestamp_local(0) 

@scriven33

{{ trigger.json.timestamp | multiply(1/1000) | timestamp_local }}

or

{{ trigger.json.timestamp | multiply(1/1000) | as_datetime }}

That would explain why I couldn’t get it to work when I tried before I posted. I checked it using the time/date conversion site linked above and got the right result, so I thought the number was right, but didn’t think to divide it. Put that new entry in and it was working immediately.

Thanks for your help @parautenbach and @petro - got there in the end.

1 Like

Dear people,

I am sorry that I might not be have putting so much effort in this an reading all the posts here.

I need your help.

I want to let HA notify me of an upcoming calendar event with his kind of message and its code :

service: notify.notify
data:
title: Upcoming Calendar Event !
message: >-
“Event :{{ trigger.calendar_event.summary }} @ {{((
as_timestamp(trigger.calendar_event.start) ) | timestamp_custom(’%X’) |
string)[0:5]}} from icloud Calendar(name(d)) Thuis as (Not ALL Day Event) in
{{ (trigger.offset | as_local).strftime(”%-I:%M")}} - Event Test 8899"

the output is when the trigger offset is 13:01 minutes before the start of the event/appointment01 e.g. is (and the event name is “Test HAS calendar 46” :


Event :Test HA calendar 46 at Saturday @ 11:40:00 from icloud Calendar(name(d)) Thuis as (Not ALL Day Event) in -1 day, 23:47:00 - Event Test 889

But I really would like to say it like this (output) :

Event :Test HA calendar 46 at Saturday @ 11:40:00 from icloud Calendar(name(d)) Thuis as (Not ALL Day Event) in 13 minutes - Event Test 889

or when the offset is 1 hour and 15 minutes (so before the event :

Event :Test HA calendar 46 at Saturday @ 11:40:00 from icloud Calendar(name(d)) Thuis as (Not ALL Day Event) in 1 hour and 15 minutes - Event Test 889

Here are some more examples of output of the same code with different offsets (times before the event starts :

Event :Test HA calendar 46 at Saturday @ 11:40:00 from icloud Calendar(name(d)) Thuis as (Not ALL Day Event) in -1 day, 23:54:46 - Event Test 889
---------------------------------------------------------------------------- when 05:14 minutes before-----------

please help me with the conversion at least and maybe withe the calculation.

THANK YOU VERY MUCH !!

Ps: Before using trigger.offset I tried to compare the now() time and the start time of the calendar event (= trigger.calendar_event.start) in a calculation and put that as a nice time string in there till the event . but that got me even further into the rabbit hole/desperate. (my automation malfunctioned completely)
(a frustrated & desperate user)

Another veision would be :

service: notify.persistent_notification
data:
title: Upcoming Calendar Event !
message: >-
Event :{{ trigger.calendar_event.summary }} at {{((
as_timestamp(trigger.calendar_event.start) ) | timestamp_custom(’%X’) |
string)[0:5]}} from icloud Calendar(name(d)) Thuis as (Not ALL Day
Event) in {{trigger.offset | string }} - Event Test 889

with output (05:14 minute before the calandar event starts:

Event :Test HA calendar 47 at 11:55 from icloud Calendar(name(d)) Thuis as (Not ALL Day Event) in -1 day, 23:54:46 - Event Test 889

The trigger.offset returns a timedelta object, so you would have to use functions and methods that apply to that type of object. I would recommend that you set up the Easy Time Macros. Once you have that set up, your template would be as follows:

service: notify.notify
data:
title: Upcoming Calendar Event !
message: >-
  {% from 'easy_time.jinja' import custom_time %}
  {% set start = trigger.calendar_event.start | as_datetime  %}
  “Event :{{ trigger.calendar_event.summary }} @ {{ start.strftime('%H:%M') }} 
  from icloud Calendar(name(d)) Thuis as (Not ALL Day Event) in {{ custom_time( start, 'hour, minute') }} - Event Test 8899"

Help… can’t get it to work…

{{ ((as_datetime(states("sensor.washing_machine_washer_completion_time")) - now())) }}

results in

0:21:08.894172

I just need the hour and minutes… but can’t find a way to remove the seconds. What am I missing?

I am sure there is an easier way but this will work. It coverts time to seconds and works from there. I don’t have your sensor so I used sun2 dawn.

{% set sec = -(states("sensor.home_sun_dawn") | as_timestamp - now() | as_timestamp) %}
{{ sec }}
{% set hours = (sec / 3600) | int(0) %}
{{ hours }}
{% set minute = ((sec - hours * 3600) / 60) | int(0) %}
{{ minute }}
{{ hours~':'~minute }}

Here it is in the developer

you may need to remove the negative sign in front of the sec = -(

Looks like I found a way by using UNIX timestamps:

{{ (as_timestamp(states("sensor.washing_machine_washer_completion_time")) - as_timestamp(now())) | timestamp_custom("%H:%M")}}

After playing quite some time with my ‘time topic’ without success, I am reaching out to the swarm intelligence of the homeassistant forum.

What I want to achieve:
Create a template binary_sensor that indicates whether it’s nighttime, I want to use it in my automations as a general guard whether the automation should run, or not.

pseudo code:
begin_nighttime <= now < end_nighttime

or in a bit more realistic but still pseudo code:
(begin_nighttime <= now() ) && ( now() < end_nighttime)

to avoid troubles caused by the reset of the hours at midnight we could rephrase the condition by checking for daytime and then negating it:
! ( ( now() >= end_nighttime) && (begin_nighttime > now() ) )

For easier maintenance via a dashboard card (WAF = Wife Acceptance Factor) I’ve created input_datetime helpers that only contain the time.

  • input_datetime.nighttime_start
  • input_datetime.nighttime_end

I want to combine them with now() to create the template binary_sensor.

But I am miserably failing. And would appreciate any help.

For Input datetimes that are time-only and a “night time” that crosses midnight use an or:

{{ today_at(states('input_datetime.nighttime_end')) > now() or
 today_at(states('input_datetime.nighttime_start')) <= now()  }}

wow @Didgeridrew
thanks a lot for the very fast reply.

your solutions works :slight_smile: if midnight is between start and end.

I wasn’t aware of today_at

but I think we need to care for the cases when midnight is not between start and end, just because people define start to be after midnight - might be the case on weekends… and people would have to sets of start/end pairs: one for workdays and one for non-workdays.

Now I am combining your hint with an if-statement.
It seems to work

{% set ts = today_at(states('input_datetime.nighttime_start_workday')) %}
{% set te = today_at(states('input_datetime.nighttime_end_workday')) %}
{% set tn = now() %}

{% if (ts > te) %} ## midnight not crossed
  {% set night = not ((tn >= te) and (ts > tn)) %}
{% else %}         ## midnight crossed
  {% set night = ((tn  < te) and (ts < tn)) %}
{% endif %}

Nighttime: {{ night }}

Those users would likely be better off just using a Schedule Helper to create the binary sensor.

:hushed:
didn’t think about schedule helper. shame on me.

let me check how it could be edited in a lovelace card.

Schedule helper can only differentiate different days of the week, but is not aware of holidays.
I use the workday integration to have a sensor to indicate a working day, it is aware of local holidays and weekends of course.

I think this one works

{% if (states('binary_sensor.workday_sensor') == 'on') %}
  {% set te = today_at(states('input_datetime.nighttime_end_workday')) %}
  {% set ts = today_at(states('input_datetime.nighttime_start_workday')) %}
{% else %}
  {% set te = today_at(states('input_datetime.nighttime_end_non_workday')) %}
  {% set ts = today_at(states('input_datetime.nighttime_start_non_workday')) %}
{% endif %}
{% set tn = now() %}

{% if (ts > te) %} ## midnight not crossed
  {% set night = not ((tn >= te) and (ts > tn)) %}
{% else %}         ## midnight crossed
  {% set night = ((tn  < te) and (ts < tn)) %}
{% endif %}
{{ night }}

and it’s only possible because of your hint about today_at

Thanks again!

I am often traveling and need to know the time of my phone (iOS device). I have the timezone of my phone in the (string) format “Europe/Berlin”. How do I template that into something that gives a UNIX timestamp (e.g. "now() in the time zone my phone is in)?

easiest way is install the custom component GitHub - pnbruckner/ha-entity-tz: Home Assistant Entity Time Zone Sensor which does all that for you and much more

1 Like

Amazing, thanks!

1 Like

Hi all,

I have various hi/lo data collected from a local weather station via MQTT (example data below), and I would like to convert the time component to 12 hour time (such as 0:03 displayed as 12:03 am). I can display the time as received from MQTT but have had no luck converting to the preferred format.

any suggestions on how to achieve this?

“hltempin”: [
66.2,
69.1,
“5:10”,
“0:03”,
75.2,
66.2,
87,
58
],

make a timestamp device_class sensor. Your template would be {{ today_at(value_json.hltempin[2]) }} and {{ today_at(value_json.hltempin[3]) }}