Dealing with time/date in attributes

I’m learning Python and developing Home Assistant integrations and would like to understand what the proper way is to deal with time and dates in sensor attributes.

  • Is there a special format for timestamps that I should use?
  • What is the right way to format the timestamp data when I display this attribute in Lovelace?
  • How can the Lovelace display consider the locale settings of the user?

Currently, the integration formats the timestamp to what I would like to see in the frontend, including locale / language setting. My feeling is, that this is not the best way to do it, as it hardwires everything. However, putting in some sort of generic timestamp leaves me with the challenge of getting the formating right in the frontend, especially if I would like to use existing cards.

I couldn’t find any pointers in the development docs. Any insight?

ISO 8601

You should be using Datetime objects for attributes or the state if you’re using device_class: timestamp. Just make sure the datetime object is timezone aware.

if you’re forced to use a string, use .isoformat() from the datetime object, which outputs to the ISO8601 standard that tom_i pointed out.

1 Like

Thanks for the quick reply.

And how do I show that in a nice, human readable way in a card in Lovelace? E.g., showing just the weekday in my chosen language?

Edit: ah, I guess it is templates as discussed here: Adapting the time format YYYY-MM-DDThh:mm:ss for template sensor / timestamp command


Ok, so using ISO8601 in the integration is straight forward. Thanks.

In the frontend, I use

as_timestamp(state_attr(config.entity, 'last_update')) | timestamp_custom('%-H:%M Uhr am %A')

for the formating, which works in principle. However, the language used for the day in %A is always English, no matter what setting a user has in HA.

So my third question is still open. Any pointers?