Extract year, month, day, hour, minute, second from variable in template

I’m struggling with getting the year, month, day, hour, minute and second out of a variable.

I know I can use now().year, etc… but as I want to extract timestamps in different formats and I don’t want any difference between them caused by any delay. So I don’t want to use now() multiple times.

So I catched the timestamp in the variable ‘timestamp’. In python I then would extract the year using timestamp.year, but it won’t work in templating…

My question is, how can I extract year from my variable ‘timestamp’?

Below my code:

   variables:
     timestamp: "{{ now() }}"
     timestamp_readable: "{{ timestamp.day }}-{{ timestamp.month }}-{{ timestamp.year }} {{ timestamp.hour }}:{{ timestamp.minute }}:{{ timestamp.second }}"
     timestamp_filename: "{{ timestamp.year }}_{{ timestamp.month }}_{{ timestamp.day }}_{{ timestamp.hour }}_{{ timestamp.minute }}_{{ timestamp.second }}"
     starttime: "{{ as_timestamp(timestamp) - 5 }}"
     endtime: "{{ as_timestamp(timestamp) + 5 }}"

example

{{(package.timestamp|as_local).date().strftime("%A %_d %B %Y")}}

Thnx! I would never found out this myself :slight_smile:

Took me a while too!

While it is working in the template editor, unfortunately I couldn’t get it to work in my script. It could be my mistake, because I don’t know what I’m doing exactly…

I tried two different ways:

  1. Declaring a variable, but I can’t use strftime to declare a variable because the editor turns red and I can’t save.
variables:
  timestamp: "{{ now() }}"
  timestamp_readable: "{{ (timestamp|as_local).date().strftime("%a %H:%M:%S") }}"
  1. Also templating in an action doesn’t work, running the script returns an error:
- service: notify.mobile_app_xxx_mobiel
  data:
    message: "Doorbell! {{ (timestamp|as_local).date().strftime("%a %H:%M:%S") }}"
failed to call service
Error rendering data template: AttributeError: 'str' object has no attribute 'tzinfo'

I found another solution, found in this post:
{{ timestamp | as_datetime | as_timestamp | timestamp_custom('%m-%-d %H:%M') }}

This one works

If the value of the variable timestamp is simply now() then this template:

{{ timestamp | as_datetime | as_timestamp | timestamp_custom('%m-%-d %H:%M') }}

can be reduced to this:

{{ now().timestamp() | timestamp_custom('%m-%-d %H:%M') }}