def format_time(total_seconds, written_time=False):
    """Format time (either "HH:MM:SS" or "H hours, M minutes and S seconds".

    Args:
        total_seconds (int): the total number of seconds
        written_time (bool): whether to write time in written language

    Returns:
        str: a string representation of the total time

    If ``written_time`` is ``True``, time will be displayed as "H hours, M
    minutes and S seconds". Otherwise, the time will be represented as
    HH:MM:SS.

    """
    time_fmt = '{hours:02d}:{minutes:02d}:{seconds:02d}'
    minutes, seconds = divmod(total_seconds, 60)
    hours, minutes = divmod(minutes, 60)
    if not written_time:
        return time_fmt.format(seconds=seconds, minutes=minutes, hours=hours)
    written_time = []
    if hours > 0:
        written_time.append('{} hour{}'.format(hours, 's' if hours > 1 else '')
            )
    if minutes > 0:
        written_time.append('{} minute{}'.format(minutes, 's' if minutes > 
            1 else ''))
    if seconds > 0:
        written_time.append('{} second{}'.format(seconds, 's' if seconds > 
            1 else ''))
    if len(written_time) == 0:
        return 'no time'
    if len(written_time) == 1:
        return written_time[0]
    return ', '.join(written_time[:-1]) + ' and ' + written_time[-1]
