def ensure_datetime(dt):
    """
    Attempts to convert an object to a UTC datetime.

    Accepts the following:
    - A `datetime` instance.
    - A `numpy.datetime64` instance.
    - `"now"`, for the current datetime.
    - A "YYYY-MM-DD HH:MM:SS" string, assumed to be UTC.
    - A "YYYY-MM-DDTHH:MM:SSZ" ISO 8601 string.
    """
    if isinstance(dt, datetime.datetime):
        return dt

    # Check for numpy.datetime64.  We just try to convert it like this to avoid
    # importing numpy, if it hasn't been yet.
    try:
        item = dt.item()
    except:
        pass
    else:
        if isinstance(item, datetime.datetime):
            return item.replace(tzinfo=UTC)

    if dt == "now":
        return datetime.datetime.utcnow().replace(tzinfo=UTC)
        
    def from_parts(ye, mo, da, ho=0, mi=0, se=0):
        try:
            return datetime.datetime(ye, mo, da, ho, mi, se, tzinfo=UTC)
        except ValueError:
            raise TypeError("not a datetime: {!r}".format(dt))

    if isinstance(dt, str):
        for regex in _DATETIME_REGEXES:
            match = regex.match(dt)
            if match is not None:
                ye = int(match.group("ye"))
                mo = int(match.group("mo"))
                da = int(match.group("da"))
                ho = int(if_none(match.group("ho"), 0))
                mi = int(if_none(match.group("mi"), 0))
                se = int(if_none(match.group("se"), 0))
                return from_parts(ye, mo, da, ho, mi, se)

    raise TypeError("not a datetime: {!r}".format(dt))
dataset/ETHPy150Open twosigma/ngrid/ngrid/datetime.py/ensure_datetime/original