Convert Token expiry to date timestamp

I’m trying to convert token expiry to date time stamp.
For example:
expires_at: 1643539008
is equal to
Sunday, 30 January 2022 10:36:48 AM

I’ve rest sensor and I want to convert the expiry to timestamp

sensor:
  - platform: rest
    name: my_token
    resource: https://xxx
    method: POST
    username: xxx
    password: xxx
    authentication: basic
    headers:
      Auth: API
    json_attributes:
      - access_token
      - expires_at
    value_template: >
      {% if value_json.access_token is defined %}
        {{ THIS IS WHERE I WANT TO DISPLAY CONVERSION  }}
      {% else %}
        KO
      {% endif %}
    scan_interval: 3600

This will give you the date and time in UTC:

{{ as_datetime(value_json.access_token) }}

Or local time:

{{ as_datetime(value_json.access_token)|as_local }}

Thanks Tom,
I had to change it to:

    value_template: >
      {% if value_json.access_token is defined %}
        OK
      {% else %}
        KO
      {% endif %}
    scan_interval: 3600

as I was getting 255 character limit error for json value_template with your conversion code added. However, your conversion is working, I just have to create a template to display the value.
Now I need to convert the time back to UTC to fed back into the system to retrieve the data for the duration.
I tried: {{as_timestamp('2022-01-30 21:00')}} but this gives me
1643536800.0
which is not right, any suggestions ?

How?

This was the data you said you were getting:

That is exactly what this gives you:

{{ as_datetime(1643539008) }}2022-01-30 10:36:48+00:00

Perhaps start again.

Post the actual data you are receiving and the format you want it in.

I was passing the token value to another REST sensor. When I tried to display the expires_at value by time casting the second sensor wasn’t working. Although the token and expires_at were generated. I just found out that in the second sensor the scan_interval was 600 and once I removed that it worked fine :slight_smile:

The issue is still the conversion value within the REST sensor value_template.
If I test in the Development template {{ state_attr(‘sensor.my_token’,‘expires_at’) }}
It gives me the right value but in the Development tool the state was
None
Then I did {{ as_datetime(value_json.access_token | int) }}
It displays 1970-01-01 00:00:00+00:00
However, it should display the state as
2022-01-30 19:00:00+00:00
based on the expires_at actual value.