简体   繁体   中英

Get id having the latest datetimestamp from dict

I am looking to retrieve the Machine VM id which has the latest creation datetimestamp value,

Below is the code but it returns incorrect value m3 .

def get_machine_id_latest_datetimestamp(self):
    thisdict = {
        "machines-xyz-123": {
            "vm": {
                "id": "m1",
                "createTimestamp": "2020-11-27T09:44:02.272908941Z",
                "status": "running"
            }
        },

        "machines-abc-567": {
            "vm": {
                "id": "m2",
                "createTimestamp": "2020-11-27T23:15:22.212021105Z",
                "status": "running"
            }
        },

        "machines-vvy-569": {
            "vm": {
                "id": "m3",
                "createTimestamp": "2020-11-27T22:18:00.572021105Z",
                "status": "running"
            }
        },

        "machines-tgh-m4": {
            "vm": {
                "id": "m4",
                "createTimestamp": "2020-11-27T14:01:22.412621105Z",
                "status": "running"
            }
        }
    }


    machine_id_timestamp_dictionary = {}
    machines_count = len(thisdict)
    machine = list(thisdict.keys())

    for i in range (machines_count):
        machine_id = thisdict[machine[i]]["vm"]["id"]
        vw_creation_timestamp = \
            thisdict[machine[i]]['vm']['createTimestamp']
        machine_id_timestamp_dictionary[machine_id] = vw_creation_timestamp

    latest_created_machine_id = 0
    machine_filtered = set()

    for machine_id in machine_id_timestamp_dictionary:
        if machine_id_timestamp_dictionary[machine_id] > thisdict[machine[i]]['vm']['createTimestamp']:
            latest_created_machine_id = machine_id
            machine_filtered.add(latest_created_machine_id)
    print("Latest Created Machine ID")
    print(latest_created_machine_id)

Ideally the Machine ID m2 should be returned as it is the latest created id, Any pointers why the code is failing?

Below. The idea is to scan the dict values, convert each date string into datetime and find the maximum.

from datetime import datetime

d = {
    "machines-xyz-123": {
        "vm": {
            "id": "m1",
            "createTimestamp": "2020-11-27T09:44:02.272908941Z",
            "status": "running"
        }
    },

    "machines-abc-567": {
        "vm": {
            "id": "m2",
            "createTimestamp": "2020-11-27T23:15:22.212021105Z",
            "status": "running"
        }
    },

    "machines-vvy-569": {
        "vm": {
            "id": "m3",
            "createTimestamp": "2020-11-27T22:18:00.572021105Z",
            "status": "running"
        }
    },

    "machines-tgh-m4": {
        "vm": {
            "id": "m4",
            "createTimestamp": "2020-11-27T14:01:22.412621105Z",
            "status": "running"
        }
    }
}


def _as_dt(x):
    return datetime.strptime(x[:19], '%Y-%m-%dT%H:%M:%S')


values = list(d.values())
latest = values[0]['vm']['id']
latest_date = _as_dt(values[0]['vm']['createTimestamp'])
for i in range(1, len(values)):
    dt = _as_dt(values[i]['vm']['createTimestamp'])
    if dt > latest_date:
        latest_date = dt
        latest = values[i]['vm']['id']
print(f'Latest vm: {latest}')

output

Latest vm: m2

Since you have ISO format timestamps, you can sort on string (skipping the conversion to datetime is more efficient). Set reverse=True and just pick the first element:

# assuming 'd' holds your nested dicts:
sortedDicts = sorted(d.values(), key=lambda d: d['vm']['createTimestamp'], reverse=True)

newestVmId = sortedDicts[0]['vm']['id']

print(newestVmId)
# m2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM