from datetime import datetime
from dateutil import tz


def date_iso(date):
    """Convert a datetime string into ISO 8601 format.

    HTML date format agrees with ISO 8601 (see also, :RFC:`3339`), ie::

        YYYY[-MM[-DD]][Thh[:mm[:ss[.s]]]T]

    For more information:

    * `Date and Time Formats:
      <https://www.w3.org/TR/NOTE-datetime>`_
    * `Date formats:
      <https://www.w3.org/International/questions/qa-date-format>`_

    :param date: Datetime object
    :type date: datetime.datetime
    :return: Datetime formatted as ISO 8601, or empty string if invalid
    :rtype: str

    .. note::
        If the datetime object is timezone naïve, it'll be localized to
        UTC, so the feed parser, and any other function that requires
        timezone aware datetime objects, do not raise an exception.
    """
    if date and not datetime.strftime(date, '%z'):
        date = date.replace(tzinfo=tz.tzutc())
    return datetime.isoformat(date, timespec='minutes') if date else ''