Takes an integer GPS time, either given as int or lal.LIGOTimeGPS, and
    converts it to a string. If a LIGOTimeGPS with nonzero decimal part is
    given, raises a ValueError.
194205
def int_gps_time_to_str(t):
    """"""

    if isinstance(t, int):
        return str(t)
    elif isinstance(t, float):
        # Wouldn't this just work generically?
        int_t = int(t)
        if abs(t - int_t) > 0.:
            raise ValueError('Need an integer GPS time, got %s' % str(t))
        return str(int_t)
    elif isinstance(t, lal.LIGOTimeGPS):
        if t.gpsNanoSeconds == 0:
            return str(t.gpsSeconds)
        else:
            raise ValueError('Need an integer GPS time, got %s' % str(t))
    else:
        err_msg = "Didn't understand input type {}".format(type(t))
        raise ValueError(err_msg)
321591
def _postprocess(valuestr):
    
    # USGS has started quoting time sometimes.  Grr, strip quotes in this case
    intpattern = re.compile(r'^\-?\d+$')
    floatpattern = re.compile(r'^\-?\d+\.\d+(E[+-]?\d\d+)?$')
    datedtpattern = '%Y-%m-%d'
    datedttimepattern = '%Y-%m-%dT%H:%M:%SZ'
    timedtpattern = '%H:%M:%S.%f'
    timepattern = re.compile(r'^\d{2}:\d{2}:\d{2}(\.\d{6})?')
    if valuestr.startswith('"') and valuestr.endswith('"'):
        # it's a string
        return valuestr[1:-1]
    elif re.match(intpattern, valuestr):
        # it's an integer
        return int(valuestr)
    elif re.match(floatpattern, valuestr):
        # floating point number
        return float(valuestr)
    # now let's try the datetime objects; throws exception if it doesn't match
    try:
        return datetime.datetime.strptime(valuestr, datedtpattern).date()
    except ValueError:
        pass
    try:
        return datetime.datetime.strptime(valuestr, datedttimepattern)
    except ValueError:
        pass
    # time parsing is complicated: Python's datetime module only accepts
    # fractions of a second only up to 6 digits
    mat = re.match(timepattern, valuestr)
    if mat:
        test = mat.group(0)
        try:
            return datetime.datetime.strptime(test, timedtpattern).time()
        except ValueError:
            pass

    # If we get here, we still haven't returned anything.
    logging.info(
        "The value %s couldn't be parsed as " % valuestr
        + "int, float, date, time, datetime. Returning it as string.")
    return valuestr
1271968
def timetopythonvalue(time_val):
    ""
    if isinstance(time_val, sequence):
        return map(timetopythonvalue, time_val)
    elif isinstance(time_val, numeric):
        return datetime.datetime(*(time.gmtime(time_val))[:6])
    elif isinstance(time_val, numeric):
        values = []
        try:
            values = map(long, time_val.split(","))
        except:
            pass
        if values:
            return map(timetopythonvalue, values)
    raise ValueError(repr(time_val))
882867
function convertToTimestamp(value) {
    if (value instanceof Date) {
      return value.getTime();
    } else if (typeof value === 'number') {
      return Math.floor(value);
    } else if (typeof value === 'string') {
      return Date.parse(value);
    } else {
      return NaN;
    }
  }
745950
def _str_datetime_now(self, x=None):
        
        if (x == 'now'):
            # Now, this is wht datetime_to_str() with no arg gives
            return(datetime_to_str())
        try:
            # Test for number
            junk = x + 0.0
            return datetime_to_str(x)
        except TypeError:
            # Didn't look like a number, treat as string
            return x
1383
def value_to_python(self, value):
        
        if not isinstance(value, bytes):
            raise tldap.exceptions.ValidationError("should be a bytes")

        try:
            value = int(value)
        except (TypeError, ValueError):
            raise tldap.exceptions.ValidationError("is invalid integer")

        try:
            value = datetime.date.fromtimestamp(value * 24 * 60 * 60)
        except OverflowError:
            raise tldap.exceptions.ValidationError("is too big a date")

        return value
693484
def _StrftimeGm(value, unused_context, args):
    
    time_tuple = time.gmtime(value)
    return _StrftimeHelper(args, time_tuple)
1267429
def extract_gps_time(self):
        '''
        
        '''
        gps_date_field = "GPS GPSDate"
        gps_time_field = "GPS GPSTimeStamp"
        gps_time = 0
        if gps_date_field in self.tags and gps_time_field in self.tags:
            date = str(self.tags[gps_date_field].values).split(":")
            if int(date[0]) == 0 or int(date[1]) == 0 or int(date[2]) == 0:
                return None
            t = self.tags[gps_time_field]
            gps_time = datetime.datetime(
                year=int(date[0]),
                month=int(date[1]),
                day=int(date[2]),
                hour=int(eval_frac(t.values[0])),
                minute=int(eval_frac(t.values[1])),
                second=int(eval_frac(t.values[2])),
            )
            microseconds = datetime.timedelta(
                microseconds=int((eval_frac(t.values[2]) % 1) * 1e6))
            gps_time += microseconds
        return gps_time
279203
def string_to_timestamp(timestring):
    

    ts = None

    # Uses an extended version of Go's duration string.
    try:
        delta = durationpy.from_str(timestring);
        past = datetime.datetime.utcnow() - delta
        ts = calendar.timegm(past.timetuple())
        return ts
    except Exception as e:
        pass

    if ts:
        return ts
    # else:
    #     print("Unable to parse timestring.")
    return 0
780411
def value_as_datetime(self):
        ''' 

        '''
        if self.value is None:
            return None
        v1, v2 = self.value
        if isinstance(v1, numbers.Number):
            d1 = datetime.utcfromtimestamp(v1 / 1000)
        else:
            d1 = v1
        if isinstance(v2, numbers.Number):
            d2 = datetime.utcfromtimestamp(v2 / 1000)
        else:
            d2 = v2
        return d1, d2
1293722
def str2dt(s):
    """"""
    return datetime.datetime.strptime(s, _FMTS if s.count(":") == 2 else _FMT if s.count(":") == 1 else _FMT0)
1033887
def _type_convert(self, value):
        
        if value is None:
            return value

        try:
            return datetime.datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
        except ValueError:
            pass

        try:
            return int(value)
        except ValueError:
            pass

        try:
            return decimal.Decimal(value)
        except decimal.InvalidOperation:
            pass

        return value
1085908
def parse_time
      s0 = @current_pos
      if match_str("T") != :failed
        s2 = match_digits
        if parse_nl != :failed
          @reported_pos = s0
          s0 = { "now" => sec2time(s2.join.to_i) }
        else
          @current_pos = s0
          s0 = :failed
        end
      else
        @current_pos = s0
        s0 = :failed
      end
      s0
    end
309668
def parse(
        self,
        time,  # type: str
        fmt,  # type: str
        now,  # type: pendulum.DateTime
        locale=None,  # type:  typing.Union[str, None]
    ):  # type: (...) -> dict
        
        escaped_fmt = re.escape(fmt)

        tokens = self._FROM_FORMAT_RE.findall(escaped_fmt)
        if not tokens:
            return time

        if not locale:
            locale = pendulum.get_locale()

        locale = Locale.load(locale)

        parsed = {
            "year": None,
            "month": None,
            "day": None,
            "hour": None,
            "minute": None,
            "second": None,
            "microsecond": None,
            "tz": None,
            "quarter": None,
            "day_of_week": None,
            "day_of_year": None,
            "meridiem": None,
            "timestamp": None,
        }

        pattern = self._FROM_FORMAT_RE.sub(
            lambda m: self._replace_tokens(m.group(0), locale), escaped_fmt
        )

        if not re.match(pattern, time):
            raise ValueError("String does not match format {}".format(fmt))

        re.sub(pattern, lambda m: self._get_parsed_values(m, parsed, locale, now), time)

        return self._check_parsed(parsed, now)
909862
def to_timestamp(self, value):
        
        if isinstance(value, (six.integer_types, float, six.string_types)):
            try:
                return int(value)
            except ValueError:
                value = self.datetime_str_to_datetime(value)

        if isinstance(value, datetime.datetime):
            if timezone.is_aware(value):
                value = timezone.localtime(value, timezone.utc)
            return self._datetime_to_timestamp(value)

        raise exceptions.ValidationError(
            "Unable to convert value: '%s' to timestamp" % value,
            code="invalid_timestamp"
        )
809865
def _parse_time(self, value):
        
        try:
            # Default time unit is a second, we should convert it to milliseconds.
            return int(value) * 1000
        except ValueError:
            # Try to parse if we are unlucky to cast value into int.
            m = self.time_format.match(value)
            if not m:
                raise ValueError("Could not parse time represented by '{t}'".format(t=value))
            time = int(m.group('time'))
            if m.group('units') != 'ms':
                time *= 1000
            return time
6273
def asn1_generaltime_to_seconds(timestr):
    
    res = None
    timeformat = "%Y%m%d%H%M%S"
    try:
        res = datetime.strptime(timestr, timeformat + 'Z')
    except ValueError:
        try:
            res = datetime.strptime(timestr, timeformat + '%z')
        except ValueError:
            pass
    return res