from datetime import datetime


def _is_key_expired(key, expiration_in_days):
    """
    Whether or not service account key is expired based on when it was created
    and the current time.

    Args:
        key (dict): API return for a service key
            .. code-block:: python

                {
                    "name": string,
                    "privateKeyType": enum(ServiceAccountPrivateKeyType),
                    "keyAlgorithm": enum(ServiceAccountKeyAlgorithm),
                    "privateKeyData": string,
                    "publicKeyData": string,
                    "validAfterTime": string,
                    "validBeforeTime": string,
                }
        expiration_in_days (int): Days before expiration of key

    Returns:
        bool: Whether or not service account key is expired
    """
    expired = False
    google_date_format = "%Y-%m-%dT%H:%M:%SZ"
    creation_time = datetime.strptime(key["validAfterTime"], google_date_format)
    current_time = datetime.strptime(
        datetime.utcnow().strftime(google_date_format), google_date_format
    )
    current_life_in_seconds = (current_time - creation_time).total_seconds()

    # seconds / seconds_per_minute / minutes_per_hour / hours_per_day
    current_life_in_days = current_life_in_seconds / 60 / 60 / 24

    if current_life_in_days >= expiration_in_days:
        expired = True

    return expired