def _get_client_by_hostname(self, hostname):
    """Search GRR by hostname and get the latest active client.

    Args:
      hostname: hostname to search for.

    Returns:
      GRR API Client object

    Raises:
      DFTimewolfError: if no client ID found for hostname.
    """
    # Search for the hostname in GRR
    print('Searching for client: {0:s}'.format(hostname))
    try:
      search_result = self.grr_api.SearchClients(hostname)
    except grr_errors.UnknownError as exception:
      self.state.add_error('Could not search for host {0:s}: {1!s}'.format(
          hostname, exception
      ), critical=True)
      return None

    result = []
    for client in search_result:
      if hostname.lower() in client.data.os_info.fqdn.lower():
        result.append((client.data.last_seen_at, client))

    if not result:
      self.state.add_error(
          'Could not get client_id for {0:s}'.format(hostname), critical=True)
      return None

    last_seen, client = sorted(result, key=lambda x: x[0], reverse=True)[0]
    # Remove microseconds and create datetime object
    last_seen_datetime = datetime.datetime.utcfromtimestamp(
        last_seen / 1000000)
    # Timedelta between now and when the client was last seen, in minutes.
    # First, count total seconds. This will return a float.
    last_seen_seconds = (
        datetime.datetime.utcnow() - last_seen_datetime).total_seconds()
    last_seen_minutes = int(round(last_seen_seconds / 60))

    print('{0:s}: Found active client'.format(client.client_id))
    print('Found active client: {0:s}'.format(client.client_id))
    print('Client last seen: {0:s} ({1:d} minutes ago)'.format(
        last_seen_datetime.strftime('%Y-%m-%dT%H:%M:%S+0000'),
        last_seen_minutes))

    return client
Search GRR by hostname and get the latest active client.

    Args:
      hostname: hostname to search for.

    Returns:
      GRR API Client object

    Raises:
      DFTimewolfError: if no client ID found for hostname.