Parses UNIX timestamps and creates Time objects
769520
def parse_timestamps
      super
      @next_capture_at = Time.at(next_capture_at) if next_capture_at
      @canceled_at     = Time.at(canceled_at) if canceled_at
      @trial_start     = Time.at(trial_start) if trial_start
      @trial_end       = Time.at(trial_end)   if trial_end
    end
731838
def parse_time(time):
    ''''''
    unit = time[-1]
    if unit not in ['s', 'm', 'h', 'd']:
        print_error('the unit of time could only from {s, m, h, d}')
        exit(1)
    time = time[:-1]
    if not time.isdigit():
        print_error('time format error!')
        exit(1)
    parse_dict = {'s':1, 'm':60, 'h':3600, 'd':86400}
    return int(time) * parse_dict[unit]
11857
def parse_datetime(s): #source: http://stackoverflow.com/questions/2211362/how-to-parse-xsddatetime-format
    """"""
    m = re.match(r""" ^
        (?P<year>-?[0-9]{4}) - (?P<month>[0-9]{2}) - (?P<day>[0-9]{2})
        T (?P<hour>[0-9]{2}) : (?P<minute>[0-9]{2}) : (?P<second>[0-9]{2})
        (?P<microsecond>\.[0-9]{1,6})?
        (?P<tz>
        Z | (?P<tz_hr>[-+][0-9]{2}) : (?P<tz_min>[0-9]{2})
        )?
        $ """, s, re.X)
    if m is not None:
        values = m.groupdict()
        #if values["tz"] in ("Z", None):
        #    tz = 0
        #else:
        #    tz = int(values["tz_hr"]) * 60 + int(values["tz_min"])
        if values["microsecond"] is None:
            values["microsecond"] = 0
        else:
            values["microsecond"] = values["microsecond"][1:]
            values["microsecond"] += "0" * (6 - len(values["microsecond"]))
        values = dict((k, int(v)) for k, v in values.items() if not k.startswith("tz"))
        try:
            return datetime(**values) # , tz
        except ValueError:
            pass
    return None
855241
def _ts_parse(ts):
    """"""
    dt = datetime.strptime(ts[:19],"%Y-%m-%dT%H:%M:%S")
    if ts[19] == '+':
        dt -= timedelta(hours=int(ts[20:22]),minutes=int(ts[23:]))
    elif ts[19] == '-':
        dt += timedelta(hours=int(ts[20:22]),minutes=int(ts[23:]))
    return dt.replace(tzinfo=pytz.UTC)
1036733
def parse_time(s):
    
    result = None

    if "epoch" in s:
        epoch_time = float(s.rstrip().split(' ')[1][:-1])
        result = datetime.datetime.utcfromtimestamp(epoch_time)
    else:
        _, date_part, time_part = s.split(' ')
        year, mon, day = date_part.split('/')
        hour, minute, sec = time_part.split(':')
        result = datetime.datetime(*map(int, (year, mon, day, hour, minute, sec)))

    return result
1076078
def _parse_timestamp(timestamp):
        
        if timestamp:
            try:
                return aniso8601.parse_datetime(timestamp)
            except AttributeError:
                # raised by aniso8601 if raw_timestamp is not valid string
                # in ISO8601 format
                try:
                    return datetime.utcfromtimestamp(timestamp)
                except:
                    # relax the timestamp a bit in case it was sent in millis
                    return datetime.utcfromtimestamp(timestamp/1000)

        raise ValueError('Invalid timestamp value! Cannot parse from either ISO8601 string or UTC timestamp.')
674534
def parse_time_indices(s):
  
  if not s.startswith('['):
    s = '[' + s + ']'
  parsed = command_parser._parse_slices(s)
  if len(parsed) != 1:
    raise ValueError(
        'Invalid number of slicing objects in time indices (%d)' % len(parsed))
  else:
    return parsed[0]
1193878
def _load_timestamps(self):
        """"""
        timestamp_file = os.path.join(
            self.data_path, 'oxts', 'timestamps.txt')

        # Read and parse the timestamps
        self.timestamps = []
        with open(timestamp_file, 'r') as f:
            for line in f.readlines():
                # NB: datetime only supports microseconds, but KITTI timestamps
                # give nanoseconds, so need to truncate last 4 characters to
                # get rid of \n (counts as 1) and extra 3 digits
                t = dt.datetime.strptime(line[:-4], '%Y-%m-%d %H:%M:%S.%f')
                self.timestamps.append(t)

        # Subselect the chosen range of frames, if any
        if self.frames is not None:
            self.timestamps = [self.timestamps[i] for i in self.frames]
460215
def unixtime2str(timestamp, fmt='%Y-%m-%d %H:%M:%S'):
    
    dt = None
    try:
        timestamp = time.localtime(timestamp)
        dt = time.strftime(fmt, timestamp)
    except Exception as err:
        print(err)
    return dt
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
671768
def format_timestamp(ts):
        
        tz_info = tz.tzutc()
        return datetime.fromtimestamp(ts, tz=tz_info).strftime("%Y-%m-%dT%H:%M:%S.000Z")
1366841
def from_timestamp(
    timestamp, tz=UTC  # type: Union[int, float]  # type: Union[str, _Timezone]
):  # type: (...) -> DateTime
    
    dt = _datetime.datetime.utcfromtimestamp(timestamp)

    dt = datetime(
        dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond
    )

    if tz is not UTC or tz != "UTC":
        dt = dt.in_timezone(tz)

    return dt
882714
def parse(s, return_type=int):
    '''
    
    '''
    RE_DAY = r'([0-9]+)d(ay)?'
    RE_HOUR = r'([0-9]+)h(our)?'
    RE_MINUTE = r'([0-9]+)m(in(ute)?)?'
    RE_SECOND = r'([0-9]+)(s(ec(ond)?)?)?'

    def _parse_time_with_unit(s):
        retval = 0
        md = re.match(RE_DAY, s)
        mh = re.match(RE_HOUR, s)
        mm = re.match(RE_MINUTE, s)
        ms = re.match(RE_SECOND, s)
        if md:
            retval = 86400 * int(md.group(1))
        elif mh:
            retval = 3600 * int(mh.group(1))
        elif mm:
            retval = 60 * int(mm.group(1))
        elif ms:
            retval = int(ms.group(1))
        return retval

    if isinstance(s, (type(None), int, float)):
        return s

    if s[-1] in '0123456789':
        s += 's'

    m = re.match(r'^(%s)?(%s)?(%s)?(%s)?$' % (RE_DAY, RE_HOUR,
                                              RE_MINUTE, RE_SECOND),
                 s)
    if not m:
        raise ParseError('invalid string: "%s"' % s)

    times = [x for x in m.groups() if isinstance(x, str) and
             re.match(r'[0-9]+[a-z]+', x)]
    seconds = sum(_parse_time_with_unit(z) for z in times)

    if return_type is int:
        return seconds
    elif return_type is timedelta:
        return timedelta(seconds=seconds)
    else:
        raise TypeError('return_type "{}" is not supported.'.format(
            return_type.__name__))
770407
def parsetime(s):
    
    try:
        fields = s.split('.')
        subfields = fields[0].split(':')
        H = int(subfields[0])
        M = int(subfields[1])
        S = int(subfields[2])
        if len(subfields) > 3:
            m = int(subfields[3])
        else:
            m = 0
        if len(fields) > 1:
            m = int(fields[1])
        return (H,M,S,m)
    except:
        raise ValueError("Invalid timestamp, must be in HH:MM:SS.mmm format: " + s)
1019815
def _load_timestamps(self):
        """"""
        timestamp_file = os.path.join(self.sequence_path, 'times.txt')

        # Read and parse the timestamps
        self.timestamps = []
        with open(timestamp_file, 'r') as f:
            for line in f.readlines():
                t = dt.timedelta(seconds=float(line))
                self.timestamps.append(t)

        # Subselect the chosen range of frames, if any
        if self.frames is not None:
            self.timestamps = [self.timestamps[i] for i in self.frames]
1153096
def pretty_timestamp(timestamp, date_format='%a-%m_%d_%y:%H:%M:%S'):
    """"""
    return time.strftime(date_format,
                         time.localtime(int(str(timestamp)[:10])))
844432
def parse_string(self, timestr, subfmts):
        """"""
        # Datetime components required for conversion to JD by ERFA, along
        # with the default values.
        components = ('year', 'mon', 'mday')
        defaults = (None, 1, 1, 0)
        # Assume that anything following "." on the right side is a
        # floating fraction of a second.
        try:
            idot = timestr.rindex('.')
        except:
            fracday = 0.0
        else:
            timestr, fracday = timestr[:idot], timestr[idot:]
            fracday = float(fracday)

        for _, strptime_fmt_or_regex, _ in subfmts:
            vals = []
            #print strptime_fmt_or_regex
            if isinstance(strptime_fmt_or_regex, six.string_types):
                try:
                    #print timstr
                    #print strptime_fmt_or_regex
                    tm = time.strptime(timestr, strptime_fmt_or_regex)
                    tm.tm_hour += int(24 * fracday)
                    tm.tm_min += int(60 * (24 * fracday - tm.tm_hour))
                    tm.tm_sec += 60 * (60 * (24 * fracday - tm.tm_hour) - tm.tm_min)
                except ValueError as ex:
                    print ex
                    continue
                else:
                    vals = [getattr(tm, 'tm_' + component)
                            for component in components]

            else:
                tm = re.match(strptime_fmt_or_regex, timestr)
                if tm is None:
                    continue
                tm = tm.groupdict()
                vals = [int(tm.get(component, default)) for component, default
                        in six.moves.zip(components, defaults)]

                hrprt = int(24 * fracday)
                vals.append(hrprt)
                mnprt = int(60 * (24 * fracday - hrprt))
                vals.append(mnprt)
                scprt = 60 * (60 * (24 * fracday - hrprt) - mnprt)
                vals.append(scprt)
            return vals
        else:
            raise ValueError('Time {0} does not match {1} format'
                             .format(timestr, self.name))