Parse an ISO 8601 formatted time stamp.

        Args:
            timestamp (str): Timestamp to parse

        Returns:
            Timestamp: Parsed timestamp
161568
def parse_isoformat(timestamp):
        
        if len(timestamp) == 20:
            zone = TzOffset('+00:00')
            timestamp = timestamp[:-1]
        elif len(timestamp) == 24:
            zone = TzOffset('%s:%s' % (timestamp[-5:-2], timestamp[-2:]))
            timestamp = timestamp[:-5]
        elif len(timestamp) == 25:
            zone = TzOffset(timestamp[-6:])
            timestamp = timestamp[:-6]
        timestamp = Timestamp.strptime(timestamp, '%Y-%m-%dT%H:%M:%S')
        timestamp = timestamp.replace(tzinfo=zone)
        return timestamp
620615
def _parse_odata_timestamp(in_date):
    
    timestamp = int(in_date.replace('/Date(', '').replace(')/', ''))
    seconds = timestamp // 1000
    ms = timestamp % 1000
    return datetime.utcfromtimestamp(seconds) + timedelta(milliseconds=ms)
424510
def parse_iso8601(text):
    
    parsed = _parse_iso8601_duration(text)
    if parsed is not None:
        return parsed

    m = ISO8601_DT.match(text)
    if not m:
        raise ParserError("Invalid ISO 8601 string")

    ambiguous_date = False
    is_date = False
    is_time = False
    year = 0
    month = 1
    day = 1
    minute = 0
    second = 0
    microsecond = 0
    tzinfo = None

    if m:
        if m.group("date"):
            # A date has been specified
            is_date = True

            if m.group("isocalendar"):
                # We have a ISO 8601 string defined
                # by week number
                if (
                    m.group("weeksep")
                    and not m.group("weekdaysep")
                    and m.group("isoweekday")
                ):
                    raise ParserError("Invalid date string: {}".format(text))

                if not m.group("weeksep") and m.group("weekdaysep"):
                    raise ParserError("Invalid date string: {}".format(text))

                try:
                    date = _get_iso_8601_week(
                        m.group("isoyear"), m.group("isoweek"), m.group("isoweekday")
                    )
                except ParserError:
                    raise
                except ValueError:
                    raise ParserError("Invalid date string: {}".format(text))

                year = date["year"]
                month = date["month"]
                day = date["day"]
            else:
                # We have a classic date representation
                year = int(m.group("year"))

                if not m.group("monthday"):
                    # No month and day
                    month = 1
                    day = 1
                else:
                    if m.group("month") and m.group("day"):
                        # Month and day
                        if not m.group("daysep") and len(m.group("day")) == 1:
                            # Ordinal day
                            ordinal = int(m.group("month") + m.group("day"))
                            leap = is_leap(year)
                            months_offsets = MONTHS_OFFSETS[leap]

                            if ordinal > months_offsets[13]:
                                raise ParserError("Ordinal day is out of range")

                            for i in range(1, 14):
                                if ordinal <= months_offsets[i]:
                                    day = ordinal - months_offsets[i - 1]
                                    month = i - 1

                                    break
                        else:
                            month = int(m.group("month"))
                            day = int(m.group("day"))
                    else:
                        # Only month
                        if not m.group("monthsep"):
                            # The date looks like 201207
                            # which is invalid for a date
                            # But it might be a time in the form hhmmss
                            ambiguous_date = True

                        month = int(m.group("month"))
                        day = 1

        if not m.group("time"):
            # No time has been specified
            if ambiguous_date:
                # We can "safely" assume that the ambiguous date
                # was actually a time in the form hhmmss
                hhmmss = "{}{:0>2}".format(str(year), str(month))

                return datetime.time(int(hhmmss[:2]), int(hhmmss[2:4]), int(hhmmss[4:]))

            return datetime.date(year, month, day)

        if ambiguous_date:
            raise ParserError("Invalid date string: {}".format(text))

        if is_date and not m.group("timesep"):
            raise ParserError("Invalid date string: {}".format(text))

        if not is_date:
            is_time = True

        # Grabbing hh:mm:ss
        hour = int(m.group("hour"))
        minsep = m.group("minsep")

        if m.group("minute"):
            minute = int(m.group("minute"))
        elif minsep:
            raise ParserError("Invalid ISO 8601 time part")

        secsep = m.group("secsep")
        if secsep and not minsep and m.group("minute"):
            # minute/second separator but no hour/minute separator
            raise ParserError("Invalid ISO 8601 time part")

        if m.group("second"):
            if not secsep and minsep:
                # No minute/second separator but hour/minute separator
                raise ParserError("Invalid ISO 8601 time part")

            second = int(m.group("second"))
        elif secsep:
            raise ParserError("Invalid ISO 8601 time part")

        # Grabbing subseconds, if any
        if m.group("subsecondsection"):
            # Limiting to 6 chars
            subsecond = m.group("subsecond")[:6]

            microsecond = int("{:0<6}".format(subsecond))

        # Grabbing timezone, if any
        tz = m.group("tz")
        if tz:
            if tz == "Z":
                offset = 0
            else:
                negative = True if tz.startswith("-") else False
                tz = tz[1:]
                if ":" not in tz:
                    if len(tz) == 2:
                        tz = "{}00".format(tz)

                    off_hour = tz[0:2]
                    off_minute = tz[2:4]
                else:
                    off_hour, off_minute = tz.split(":")

                offset = ((int(off_hour) * 60) + int(off_minute)) * 60

                if negative:
                    offset = -1 * offset

            tzinfo = FixedTimezone(offset)

        if is_time:
            return datetime.time(hour, minute, second, microsecond)

        return datetime.datetime(
            year, month, day, hour, minute, second, microsecond, tzinfo=tzinfo
        )
974671
def parse_isodate(datestr):
    
    m = isodate_rx.search(datestr)
    assert m, 'unrecognized date format: ' + datestr
    year, month, day = m.group('year', 'month', 'day')
    hour, minute, second, fraction = m.group('hour', 'minute', 'second', 'fraction')
    tz, tzhh, tzmm = m.group('tz', 'tzhh', 'tzmm')
    dt = datetime.datetime(int(year), int(month), int(day), int(hour))
    if fraction is None:
        fraction = 0
    else:
        fraction = float('0.' + fraction)
    if minute is None:
        dt = dt.replace(minute=int(60 * fraction))
    else:
        dt = dt.replace(minute=int(minute))
        if second is None:
            dt = dt.replace(second=int(60 * fraction))
        else:
            dt = dt.replace(second=int(second), microsecond=int(1000000 * fraction))
    if tz is not None:
        if tz[0] == 'Z':
            offset = 0
        else:
            offset = datetime.timedelta(minutes=int(tzmm or 0), hours=int(tzhh))
            if tz[0] == '-':
                offset = -offset
        dt = dt.replace(tzinfo=UTCOffset(offset))
    return dt
234370
def from_iso_datetime(datetimestring, use_dateutil=True):
    
    if not _iso8601_datetime_re.match(datetimestring):
        raise ValueError('Not a valid ISO8601-formatted datetime string')
    # Use dateutil's parser if possible
    if dateutil_available and use_dateutil:
        return parser.isoparse(datetimestring)
    else:
        # Strip off timezone info.
        return datetime.datetime.strptime(datetimestring[:19], '%Y-%m-%dT%H:%M:%S')
932405
def _parse_timestamp(tokens):
    """"""
    def parse():
        precision = TimestampPrecision.YEAR
        off_hour = tokens[_TimestampState.OFF_HOUR]
        off_minutes = tokens[_TimestampState.OFF_MINUTE]
        microsecond = None
        fraction_digits = None
        if off_hour is not None:
            assert off_minutes is not None
            off_sign = -1 if _MINUS in off_hour else 1
            off_hour = int(off_hour)
            off_minutes = int(off_minutes) * off_sign
            if off_sign == -1 and off_hour == 0 and off_minutes == 0:
                # -00:00 (unknown UTC offset) is a naive datetime.
                off_hour = None
                off_minutes = None
        else:
            assert off_minutes is None

        year = tokens[_TimestampState.YEAR]
        assert year is not None
        year = int(year)

        month = tokens[_TimestampState.MONTH]
        if month is None:
            month = 1
        else:
            month = int(month)
            precision = TimestampPrecision.MONTH

        day = tokens[_TimestampState.DAY]
        if day is None:
            day = 1
        else:
            day = int(day)
            precision = TimestampPrecision.DAY

        hour = tokens[_TimestampState.HOUR]
        minute = tokens[_TimestampState.MINUTE]
        if hour is None:
            assert minute is None
            hour = 0
            minute = 0
        else:
            assert minute is not None
            hour = int(hour)
            minute = int(minute)
            precision = TimestampPrecision.MINUTE

        second = tokens[_TimestampState.SECOND]
        if second is None:
            second = 0
        else:
            second = int(second)
            precision = TimestampPrecision.SECOND

            fraction = tokens[_TimestampState.FRACTIONAL]
            if fraction is not None:
                fraction_digits = len(fraction)
                if fraction_digits > MICROSECOND_PRECISION:
                    for digit in fraction[MICROSECOND_PRECISION:]:
                        if digit != _ZERO:
                            raise ValueError('Only six significant digits supported in timestamp fractional. Found %s.'
                                             % (fraction,))
                    fraction_digits = MICROSECOND_PRECISION
                    fraction = fraction[0:MICROSECOND_PRECISION]
                else:
                    fraction.extend(_ZEROS[MICROSECOND_PRECISION - fraction_digits])
                microsecond = int(fraction)
        return timestamp(
            year, month, day,
            hour, minute, second, microsecond,
            off_hour, off_minutes,
            precision=precision, fractional_precision=fraction_digits
        )
    return parse
893961
def parse_iso8601_date(string):
    

    # Match ISO 8601?
    match = _RE_ISO8601_DATE.search(string)
    if not match:
        raise ValueError('Expected ISO 8601 date')

    # Extract ISO 8601 components
    year = int(match.group('year'))
    month = int(match.group('month'))
    day = int(match.group('day'))

    return date(year, month, day)
1035132
def _parse_date_iso8601(dateString):
    ''''''
    m = None
    for _iso8601_match in _iso8601_matches:
        m = _iso8601_match(dateString)
        if m:
            break
    if not m:
        return
    if m.span() == (0, 0):
        return
    params = m.groupdict()
    ordinal = params.get('ordinal', 0)
    if ordinal:
        ordinal = int(ordinal)
    else:
        ordinal = 0
    year = params.get('year', '--')
    if not year or year == '--':
        year = time.gmtime()[0]
    elif len(year) == 2:
        # ISO 8601 assumes current century, i.e. 93 -> 2093, NOT 1993
        year = 100 * int(time.gmtime()[0] / 100) + int(year)
    else:
        year = int(year)
    month = params.get('month', '-')
    if not month or month == '-':
        # ordinals are NOT normalized by mktime, we simulate them
        # by setting month=1, day=ordinal
        if ordinal:
            month = 1
        else:
            month = time.gmtime()[1]
    month = int(month)
    day = params.get('day', 0)
    if not day:
        # see above
        if ordinal:
            day = ordinal
        elif params.get('century', 0) or \
                 params.get('year', 0) or params.get('month', 0):
            day = 1
        else:
            day = time.gmtime()[2]
    else:
        day = int(day)
    # special case of the century - is the first year of the 21st century
    # 2000 or 2001 ? The debate goes on...
    if 'century' in params:
        year = (int(params['century']) - 1) * 100 + 1
    # in ISO 8601 most fields are optional
    for field in ['hour', 'minute', 'second', 'tzhour', 'tzmin']:
        if not params.get(field, None):
            params[field] = 0
    hour = int(params.get('hour', 0))
    minute = int(params.get('minute', 0))
    second = int(float(params.get('second', 0)))
    # weekday is normalized by mktime(), we can ignore it
    weekday = 0
    daylight_savings_flag = -1
    tm = [year, month, day, hour, minute, second, weekday,
          ordinal, daylight_savings_flag]
    # ISO 8601 time zone adjustments
    tz = params.get('tz')
    if tz and tz != 'Z':
        if tz[0] == '-':
            tm[3] += int(params.get('tzhour', 0))
            tm[4] += int(params.get('tzmin', 0))
        elif tz[0] == '+':
            tm[3] -= int(params.get('tzhour', 0))
            tm[4] -= int(params.get('tzmin', 0))
        else:
            return None
    # Python's time.mktime() is a wrapper around the ANSI C mktime(3c)
    # which is guaranteed to normalize d/m/y/h/m/s.
    # Many implementations have bugs, but we'll pretend they don't.
    return time.localtime(time.mktime(tuple(tm)))
652554
def parse_time(timestring):
    
    timestring = str(timestring).strip()

    for regex, pattern in TIME_FORMATS:
        if regex.match(timestring):
            found = regex.search(timestring).groupdict()

            dt = datetime.utcnow().strptime(found['matched'], pattern)
            dt = datetime.combine(date.today(), dt.time())

            if 'fraction' in found and found['fraction'] is not None:
                dt = dt.replace(microsecond=int(found['fraction'][1:]))

            if 'timezone' in found and found['timezone'] is not None:
                dt = dt.replace(tzinfo=Timezone(found.get('timezone', '')))

            return dt

    raise ParseError()
1200741
def readable_timestamp(stamp):
    
    if date.fromtimestamp(stamp) == date.today():
        return str(datetime.fromtimestamp(stamp).strftime("%I:%M:%S%p"))
    else:
        return str(date.fromtimestamp(stamp))
714226
def format_datetime(cls, timestamp):
        
        if not timestamp:
            raise DateTimeFormatterException('timestamp must a valid string {}'.format(timestamp))

        return timestamp.strftime(cls.DATETIME_FORMAT)
430395
def parse_ISO8601(time_gap):
    
    matcher = None

    if time_gap.count("T"):
        units = {
            "H": ("HOURS", isodate.Duration(hours=1)),
            "M": ("MINUTES", isodate.Duration(minutes=1)),
            "S": ("SECONDS", isodate.Duration(seconds=1))
        }
        matcher = re.search("PT(\d+)([HMS])", time_gap)
        if matcher:
            quantity = int(matcher.group(1))
            unit = matcher.group(2)
            return quantity, units.get(unit)
        else:
            raise Exception("Does not match the pattern: {}".format(time_gap))
    else:
        units = {
            "Y": ("YEARS", isodate.Duration(years=1)),
            "M": ("MONTHS", isodate.Duration(months=1)),
            "W": ("WEEKS", isodate.Duration(weeks=1)),
            "D": ("DAYS", isodate.Duration(days=1))
        }
        matcher = re.search("P(\d+)([YMWD])", time_gap)
        if matcher:
            quantity = int(matcher.group(1))
            unit = matcher.group(2)
        else:
            raise Exception("Does not match the pattern: {}".format(time_gap))

    return quantity, units.get(unit)
262857
def parse_datetime(datetimestring):
    '''
    
    '''
    try:
        datestring, timestring = re.split('T| ', datetimestring)
    except ValueError:
        raise isodate.ISO8601Error(
            "ISO 8601 time designator 'T' or ' '  missing. Unable to parse "
            "datetime string %r" % datetimestring
        )
    tmpdate = isodate.parse_date(datestring)
    tmptime = isodate.parse_time(timestring)
    return datetime.datetime.combine(tmpdate, tmptime)
778300
def get_timestamp_info(value):
    
    value, offset = _split_offset(value)
    fmt, microsec = _get_timestamp_format(value)
    dt_value = _datetime_obj_factory(value, fmt)
    return dt_value, fmt, offset, microsec
1211483
def parse_isotime(timestr):
    """"""
    try:
        return iso8601.parse_date(timestr)
    except iso8601.ParseError as e:
        raise ValueError(six.text_type(e))
    except TypeError as e:
        raise ValueError(six.text_type(e))
470209
def get_time_from_rfc3339(rfc3339):
    

    try:
        # py 3

        dt = dateutil.parser.parse(rfc3339, ignoretz=False)
        return dt.timestamp()
    except NameError:
        # py 2

        # Decode the RFC 3339 date with no fractional seconds (the
        # format Origin provides). Note that this will fail to parse
        # valid ISO8601 timestamps not in this exact format.
        time_tuple = strptime(rfc3339, '%Y-%m-%dT%H:%M:%SZ')
        return timegm(time_tuple)
1101116
def parse(input):
    '''
    
    '''
    if isinstance(input, datetime):
        return input
    if isinstance(input, date):
        return date_to_datetime(input)
    if isinstance(input, time):
        return time_to_datetime(input)
    if isinstance(input, (int, float)):
        return timestamp_to_datetime(input)
    if isinstance(input, (str)):
        return string_to_data_time(input)
    return None