Convert & compare the time and choose latest (youngest) available one to get specific ID

Hello,

I’m collecting all JSON data via REST platform where I need to find specific ID. Specific ID is bounded to specific camera record which has specified timestamp (startTime;endTime;_id). So I need to collect all data with timestamps of startTime, then compare all times from now() and show the youngest time to be able to identify latest available record from camera.

I’m referring to this project Watch Unifi Video Camera recordings from iOS Notification Center but author must receive not valid values because he just count all data and choose latest available one. But the problem is if data are being overwritten then he will not receive valid youngest ID (because it can be on first possition _id and not last one).

Here is mentioned rest platform:

  - platform: rest
    name: Latest entryway recording ID
    method: GET
    resource: 'http://someHost:7080/api/2.0/recording?apiKey=XYZABC'
    value_template: >
      {% set last = (value_json.data | count) - 1 %}
      {{ value_json.data[last]['_id'] }}

But I would like to compare all value_json.data by value_json.data.startTime and after I receive youngest data then I want to get value_json.data._id to identify the record and be able to download it.

The startTime and endTime is in milliseconds since UNIX epoch and I found timestamp_local function to convert the time. So it would look like this:

{% set startTimes = (value_json.data.startTime | timestamp_local ) %}

But I’m lost how to compare such collected times and identify the youngest.

Here is some sample how looks 2 JSON records:

eventType : motionRecording
startTime : 1558367540514
endTime : 1558367576480
locked : False
inProgress : False
markedForDeletion : False
_id : 5ce2cd443f43ba9d4864ff3f

eventType : motionRecording
startTime : 1558380512926
endTime : 1558380556956
locked : False
inProgress : False
markedForDeletion : False
_id : 5ce2fff03f46ba9d28650132

And I want to get exacly latest _id which has the youngest startTime value.

Thank you for any ideas how to solve this problem!

This should get you the earliest start time id

  - platform: rest
    name: Latest entryway recording ID
    method: GET
    resource: 'http://someHost:7080/api/2.0/recording?apiKey=XYZABC'
    value_template: >
      {% set earliest_start = value_json.data | map(attribute='startTime') | list | min %}
      {% set earliest_data = (value_json.data | selectattr('startTime','eq',earliest_start) | list )[0] %}
      {{ earliest_data._id }}
1 Like

Hi petro,

I was receiving the oldest camera record so I needed to change:

to

{% set earliest_start = value_json.data | map(attribute=‘startTime’) | list | max %}

So I got exactly newest camera record.

You just solved my problem so fast and easy! Thank you very much :+1:

Ah, I thought you wanted the earliest record. My bad.