Getting time and date with templates

Day of the week:

  - sensor:
    - name: "Day of the week"
      state: "{{ now().strftime('%A') }}"

Today’s date:

  - sensor:
    - name: "Todays date"
      state: "{{ now().strftime('%B %d %Y') }}"

The Time now:

  - sensor:
    - name: "Time now"
      state: "{{ now().strftime('%H:%M') }}"

Sunrise:

  - sensor:
    - name: "Sunrise"
      state:  "{{ as_timestamp(states.sun.sun.attributes.next_rising) | timestamp_custom ('%H:%M') }}"

Sunset:

  - sensor:
    - name: "Sunset"
      state: "{{ as_timestamp(states.sun.sun.attributes.next_setting) | timestamp_custom ('%H:%M') }}"

Sunset sensor that uses frontend date & time settings:

  - sensor:
    - name: "Sunset"
      device_class: timestamp
      state: "{{ states.sun.sun.attributes.next_setting }}"

There is a comprehensive post on handling time here:

The EPIC Time Conversion and Manipulation Thread!.

There are also some template repositories available through HACS or manual installation with very helpful time and date templates:

GitHub - Petro31/easy-time-jinja: Easy Time calculations for Home Assistant templates.
GitHub - TheFes/relative-time-plus: Relative Time Macro with additional options.

Several examples of date-based Template Conditions are shown here.

Most of the available time and date methods and functions come from Python’s datetime library. As such, it can be a great resource for information like strftime() format codes or to learn about methods that may be available and meet your needs, but just aren’t commonly mentioned on these forums.


The Home Assistant Cookbook - Index.

5 Likes