Home > database >  Python list of objects query
Python list of objects query

Time:09-15

I have a python class here:

class device:
def __init__(self, hostname, ipaddress, status, version, sensor_id, first_seen) -> None:
    self.hostname = hostname
    self.ipaddress = ipaddress
    self.status = status
    self.version = version
    self.sensor_id = sensor_id
    self.first_seen = first_seen

Lets say I have 3 instances of this which are all identical except the sensor_id and first_seen, these objects are stored in a list

sensor_list = []
dev1 = device("PC1", "1.1.1.1", "offline", "21.1", "ID_0001", "09/08/2022")
dev2 = device("PC1", "1.1.1.1", "offline", "21.1", "ID_0002", "09/09/2022")
dev3 = device("PC1", "1.1.1.1", "offline", "21.1", "ID_0003", "14/08/2022")
sensor_list.append(dev1)
sensor_list.append(dev2)
sensor_list.append(dev3)

How could I search the list of objects, and retrieve the sensor_id with the latest first_seen timestamp? Is it possible to do this using some kind of list comprehension or is it a little more complicated than that?

latest = [x for x in sensor_list ???]

CodePudding user response:

Use max()

latest = max(sensorlist, key = lambda s: datetime.strptime(s.first_seen, '%d/%m/%Y'))

It would be simpler if you converted first_seen to a datetime when you create the object rather than having to do it whenever you access the object.

  • Related