def to_iso8601(dt, tz=None):
    """
    Returns an ISO-8601 representation of a given datetime instance.

        >>> to_iso8601(datetime.datetime.now())
        '2014-10-01T23:21:33.718508Z'

    :param dt: a :class:`~datetime.datetime` instance
    :param tz: a :class:`~datetime.tzinfo` to use; if None - use a default one
    """
    if tz is not None:
        dt = dt.replace(tzinfo=tz)
    iso8601 = dt.isoformat()

    # Naive datetime objects usually don't have info about timezone.
    # Let's assume it's UTC and add Z to the end.
    if re.match(r'.*(Z|[+-]\d{2}:\d{2})$', iso8601) is None:
        iso8601 += 'Z'

    return iso8601
Returns an ISO-8601 representation of a given datetime instance.

        >>> to_iso8601(datetime.datetime.now())
        '2014-10-01T23:21:33.718508Z'

    :param dt: a :class:`~datetime.datetime` instance
    :param tz: a :class:`~datetime.tzinfo` to use; if None - use a default one