The EPIC Time Conversion and Manipulation Thread!

Sensor reports “seconds”
Output in card ( D:H:M )
image

Edit: Without template
image

Edit: Actually this seems to have change at some point, last year it was only an INT, no commas, and no trailing s :slight_smile:

That explains why it wasn’t working for me. Mine is a DTG.

OK, thanks. I wasn’t sure which format was correct or if HA was presenting it wrong.

          {% if is_state("sensor.filey_tide", "Falling") %}Low{% else %}High{%
          endif %} is {{ min(state_attr('sensor.filey_tide',
          'next_high_tide_at'), state_attr('sensor.filey_tide',
          'next_low_tide_at')) }}.

Currently, my tidal sensor outputs the full date and time - using the code above how would I get JUST the time?

CURRENT
Low is 2022-08-31 13:56:32

WHAT I NEED
Low is 13:56:32

We need more info about next_high_tide_at and what kind of object it is. Put this in the template editor please

{{ state_attr('sensor.filey_tide', 'next_high_tide_at') * 2 }}

and post the results here.

TypeError: unsupported operand type(s) for *: ‘datetime.datetime’ and ‘int’

Thanks, that means they are datetime objects, so…

          {% set info = 'Low' if is_state("sensor.filey_tide", "Falling") else 'High' %}
          {% set value = min(state_attr('sensor.filey_tide','next_high_tide_at'), state_attr('sensor.filey_tide','next_low_tide_at')) %}
          {{ info }} is {{ value.time() }}.
1 Like

I am sure this has been answered

If I have device_class: timestamp sensor (it behaves differently to a non class sensor)
How do I add a custom timestamp that can be adjusted prior to hitting HA and won’t break the original timestamp format when sending it through mqtt discovery.

It doesn’t currently have an attribute

for the sake of readability we shall name Timestamp(is the true name) to Bobtime.

{{ value_json.Bobtime }} works but no customization

{ "Bobtime": "2022-09-04T21:05:30+1000", "next": "value", } example mqtt message

I have tried a things and I am also not set as sending it as a device_class

{{ value_json.Bobtime | as_timestamp | timestamp_custom('%H:%M:%S %d-%m-%Y) }}
``` async spits that back with an error. Which I guess is understandable as it breaks the desired TS format
This works when not device_class: timestamp

{{ value.json_Bobtime | as_datetime | timestamp_custom('%H:%M:%S %d-%m-%Y) }}
Also not liked by discovery

So can I do something like

{{ value_json.Bobtime | (strptime(state_attr('Bobtime.additional, 'mini_bob') | timestamp_custom('custom timestamp variable') }}

or
Do I need to add a json_attr template, and json_attr_topic and can I steal the Bobtime to make the attribute without actually having an attribute message…

I would like the `timestamp_custom( ) to be able to be changed by “$variable” before hitting discovery

1 Like

Thanks so much…totally smashed it

{{ value_json.Bobtime | as_datetime }}

How do I customize as_datetime before it is sent.

"value_template": "{{ value_json.SunRise | as_datetime | timestamp_custom(\'%H:%M:S %z %d-%m-%Y\') }}"

Unable to parse JSON timestamp_SunRise: '{"name": "a custom SunRise", "state_topic": "homeassistant/testdiscovery/state", "device_class": "timestamp", "value_template": "{{ value_json.SunRise | as_datetime | timestamp_custom(\'%H:%M:S %z %d-%m-%Y\') }}", "unique_id": "sunrise_12345", "icon": "mdi:clock-digital", "device": { "identifiers": ["bobtime-Sensors"], "name": "BOBBIE", "model": "HAOS", "manufacturer": "HA", "sw_version": "00.11" }}'

Capture

When it is not a device timestamp

\"{{ value_json.SunRise | as_datetime }}\"

image

no device class
\"{{ value_json.SunRise | as_timestamp | timestamp_custom('%H:%M:S %z %d-%m-%Y') }}\",

tstscCapture

when it is a device class
Invalid state message '{"bobtime": "2022-09-05T11:57:22+1000", "SunRise": "2022-09-05T09:06:34+1000"}' from 'homeassistant/testdiscovery/state'

bash script paste.ee

\"{{ value_json.SunRise | as_dateime | timestamp_custom('%H:%M
   :S %z %d-%m-%Y') }}\", \"unique_id\": \"sunrise_12345\", \"device_class\": \"timestamp\",
Logger: homeassistant.util.logging
Source: util/logging.py:155
First occurred: 12:08:31 PM (1 occurrences)
Last logged: 12:08:31 PM

Exception in async_discover when dispatching 'mqtt_discovery_new_sensor_mqtt': ({'name': 'a custom SunRise', 'state_topic': 'homeassistant/testdiscovery/state', 'value_template': "{{ value_json.SunRise | as_dateime | timestamp_custom('%H:%M:S %z %d-%m-%Y') }}", 'unique_id': 'sunrise_12345', 'device_class': 'timestamp', 'icon': 'mdi:clock-digital', 'device': {'identifiers': ['bobtime-Sensors'], 'name': 'BOBBIE', 'model': 'HAOS', 'manufacturer': 'HA', 'sw_version': '00.11'}, 'platform': 'mqtt'},) Traceback (most recent call last): File "/usr/src/homeassistant/homeassistant/components/mqtt/mixins.py", line 323, in async_discover config = schema(discovery_payload) File "/usr/local/lib/python3.10/site-packages/voluptuous/validators.py", line 232, in __call__ return self._exec((Schema(val) for val in self.validators), v) File "/usr/local/lib/python3.10/site-packages/voluptuous/validators.py", line 355, in _exec raise e if self.msg is None else AllInvalid(self.msg, path=path) File "/usr/local/lib/python3.10/site-packages/voluptuous/validators.py", line 351, in _exec v = func(v) File "/usr/local/lib/python3.10/site-packages/voluptuous/schema_builder.py", line 272, in __call__ return self._compiled([], data) File "/usr/local/lib/python3.10/site-packages/voluptuous/schema_builder.py", line 818, in validate_callable return schema(data) File "/usr/local/lib/python3.10/site-packages/voluptuous/schema_builder.py", line 272, in __call__ return self._compiled([], data) File "/usr/local/lib/python3.10/site-packages/voluptuous/schema_builder.py", line 595, in validate_dict return base_validate(path, iteritems(data), out) File "/usr/local/lib/python3.10/site-packages/voluptuous/schema_builder.py", line 433, in validate_mapping raise er.MultipleInvalid(errors) voluptuous.error.MultipleInvalid: invalid template (TemplateAssertionError: No filter named 'as_dateime'.) for dictionary value @ data['value_template']

you can’t customize timestamp sensors. They need to output a datetime. If you want to customize the output, don’t set the device_class.

use with this with device_class: timestamp

{{ value_json.Bobtime | as_datetime }}

That’s with one as { value_json.SunRise } and one with{ value_json.bobtime | as_datetime}

The as_datetime doesn’t seem to do anything. Hence my question I guess. Good to know I am trying to push the proverbial uphill with the class timestamp. It would be kind of nice to be able to send it as a timestamp and have a datetime attribute. Thanks!

the as_datetime turns the string into a datetime object, which is required for timestamp device classes.

1 Like

that’s only if it’s not a device class though right? so the as datetime is superfluous. the class already declares it? whereas if its not a class you need to declare it… dunno that’s backend magic beyond me.

No, you need to return a datetime object from your template. That’s a requirement for device_class: timestamp sensors. MQTT may have special code to get around that requirement as topics are always strings.

right that makes sense. mqtt does probably handle it differently to python. or accommodates it.

I think I have a simple question, but I can’t get my head around the date and time in HA.
I am new to HA so probably this question is asked before.

Tot get the yield of my solar system for this year I have to subtract the total value - value on 31-12-“last year” 00:00:00. The EMS is only sending the total value trough MQTT.
To get this value I use a command_line with curl. The timestamp in EPOCH format has to go inside the command.

- platform: command_line
      name: Einde jaar opbrengst Zonnepanelen 
      unique_id: Einde jaar opbrengst Zonnepanelen 
      command: curl -X POST -d '{"seq":1, "method":"datalog_get_last_daily_value_before", "arguments":{"timestamp":"EPOCH timestamp 31-12-"last year" 00:00:00 ", "oid":"b02ec7bc", "prop":"export"}}' http://192.168.1.29/iungo/api_request
      value_template: "{{ value_json['rv']['value'] }}"

sorry for the Off-topic reply here, but, noticing you use the Iungo (as do I):
why dont you create an mqtt sensor for that value? The Iungo doesnt respond very well to command_line api requests, and having it publish the values is simple as can be

Hi guys,
I struggle with an automation to shift my next alarm of my phone to have it 30 minutes earlier for an automation. so this is what I did in the configuration file:

  - platform: template
    sensors:
      time_light_bedroom_alarm:
        value_template: "{{(as_timestamp(states('sensor.pixel_5_next_alarm'))-(30*60))|timestamp_local}}"

and this is what I did in the automation file:

  alias: Alarm morning routine
  description: ''
  trigger:
  - platform: time
    at: sensor.time_light_bedroom_alarm
  - platform: time
    at: sensor.pixel_5_next_alarm

the second trigger is working, but I just used to test if it is working…
Can somebody help what I do wrong?