Parse the IERS file ``Leap_Second.dat``.

    The leap dates array can be searched with::

        index = np.searchsorted(leap_dates, jd, 'right')

    The resulting index allows (TAI - UTC) to be fetched with::

        offset = leap_offsets[index]
557419
def parse_leap_seconds(fileobj):
    
    lines = iter(fileobj)
    for line in lines:
        if line.startswith(b'#  File expires on'):
            break
    else:
        raise ValueError('Leap_Second.dat is missing its expiration date')
    line = line.decode('ascii')

    with _lock:  # won't help if anyone user threads are doing parsing, alas
        original_locale = locale.setlocale(locale.LC_ALL)
        locale.setlocale(locale.LC_ALL, 'C')
        try:
            dt = datetime.strptime(line, '#  File expires on %d %B %Y\n')
        finally:
            locale.setlocale(locale.LC_ALL, original_locale)

    # The file went out of date at the beginning of July 2016, and kept
    # downloading every time a user ran a Skyfield program.  So we now
    # build in a grace period:
    grace_period = timedelta(days=30)
    expiration_date = dt.date() + grace_period
    mjd, day, month, year, offsets = np.loadtxt(lines).T
    leap_dates = np.ndarray(len(mjd) + 2)
    leap_dates[0] = '-inf'
    leap_dates[1:-1] = mjd + 2400000.5
    leap_dates[-1] = 'inf'
    leap_offsets = np.ndarray(len(mjd) + 2)
    leap_offsets[0] = leap_offsets[1] = offsets[0]
    leap_offsets[2:] = offsets
    return expiration_date, (leap_dates, leap_offsets)
730229
private static Data loadLeapSeconds(URL url) throws ClassNotFoundException, IOException {
        List<String> lines;
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) {
            lines = reader.lines().collect(Collectors.toList());
        }
        List<Long> dates = new ArrayList<>();
        List<Integer> offsets = new ArrayList<>();
        for (String line : lines) {
            line = line.trim();
            if (line.isEmpty() || line.startsWith("#")) {
                continue;
            }
            Matcher matcher = LEAP_FILE_FORMAT.matcher(line);
            if (matcher.matches() == false) {
                throw new StreamCorruptedException("Invalid leap second file");
            }
            dates.add(LocalDate.parse(matcher.group(1)).getLong(JulianFields.MODIFIED_JULIAN_DAY));
            offsets.add(Integer.valueOf(matcher.group(2)));
        }
        long[] datesData = new long[dates.size()];
        int[] offsetsData = new int[dates.size()];
        long[] taiData = new long[dates.size()];
        for (int i = 0; i < datesData.length; i++) {
            datesData[i] = dates.get(i);
            offsetsData[i] = offsets.get(i);
            taiData[i] = tai(datesData[i], offsetsData[i]);
        }
        return new Data(datesData, offsetsData, taiData);
    }
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
352516
def _parsed_string_to_bounds(date_type, resolution, parsed):
    
    if resolution == 'year':
        return (date_type(parsed.year, 1, 1),
                date_type(parsed.year + 1, 1, 1) - timedelta(microseconds=1))
    elif resolution == 'month':
        if parsed.month == 12:
            end = date_type(parsed.year + 1, 1, 1) - timedelta(microseconds=1)
        else:
            end = (date_type(parsed.year, parsed.month + 1, 1) -
                   timedelta(microseconds=1))
        return date_type(parsed.year, parsed.month, 1), end
    elif resolution == 'day':
        start = date_type(parsed.year, parsed.month, parsed.day)
        return start, start + timedelta(days=1, microseconds=-1)
    elif resolution == 'hour':
        start = date_type(parsed.year, parsed.month, parsed.day, parsed.hour)
        return start, start + timedelta(hours=1, microseconds=-1)
    elif resolution == 'minute':
        start = date_type(parsed.year, parsed.month, parsed.day, parsed.hour,
                          parsed.minute)
        return start, start + timedelta(minutes=1, microseconds=-1)
    elif resolution == 'second':
        start = date_type(parsed.year, parsed.month, parsed.day, parsed.hour,
                          parsed.minute, parsed.second)
        return start, start + timedelta(seconds=1, microseconds=-1)
    else:
        raise KeyError
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]
97596
def parse_date(value: Union[date, StrIntFloat]) -> date:
    
    if isinstance(value, date):
        if isinstance(value, datetime):
            return value.date()
        else:
            return value

    number = get_numeric(value)
    if number is not None:
        return from_unix_seconds(number).date()

    match = date_re.match(cast(str, value))
    if not match:
        raise errors.DateError()

    kw = {k: int(v) for k, v in match.groupdict().items()}

    with change_exception(errors.DateError, ValueError):
        return date(**kw)
967262
def _parse(partial_dt):
    
    dt = None
    try:
        if isinstance(partial_dt, datetime):
            dt = partial_dt
        if isinstance(partial_dt, date):
            dt = _combine_date_time(partial_dt, time(0, 0, 0))
        if isinstance(partial_dt, time):
            dt = _combine_date_time(date.today(), partial_dt)
        if isinstance(partial_dt, (int, float)):
            dt = datetime.fromtimestamp(partial_dt)
        if isinstance(partial_dt, (str, bytes)):
            dt = parser.parse(partial_dt, default=timezone.now())

        if dt is not None and timezone.is_naive(dt):
            dt = timezone.make_aware(dt)
        return dt
    except ValueError:
        return None
935433
def parse(date)
			return date if date.kind_of?(self)
			r=[]
			dates = date.to_s.chomp.split(/,\s*/)
			dates.each do |d|
				r << d.split(/\s*->\s*/).map {|i| i == ":now" ? :now : i }
			end
			return DateRange.new(r)
		end
59780
def datetimeparse(s):
    
    try:
        dt = dateutil.parser.parse(s)
    except ValueError:
        return None

    return utc_dt(dt)
1000889
function parseDate(fmt, date) {
    var indexMap = {}; // contains reGroupPosition -> typeLetter or [typeLetter, value array]
    var reIndex = 1;
    var timezoneOffsetMatch;
    var timezoneIndex;
    var match;

    var format = replace(fmt, /^\?/);
    if (format!=fmt && !trim(date))
      return _null;

    if (match = /^\[([+-])(\d\d)(\d\d)\]\s*(.*)/.exec(format)) {
      timezoneOffsetMatch = match;
      format = match[4];
    }

    var parser = new RegExp(format.replace(/(.)(\1*)(?:\[([^\]]*)\])?/g, function(wholeMatch, placeholderChar, placeholderDigits, param) {
      if (/[dmhkyhs]/i.test(placeholderChar)) {
        indexMap[reIndex++] = placeholderChar;
        var plen = placeholderDigits.length+1;
        return "(\\d"+(plen<2?"+":("{1,"+plen+"}"))+")";
      }
      else if (placeholderChar == 'z') {
        timezoneIndex = reIndex;
        reIndex += 3;
        return "([+-])(\\d\\d)(\\d\\d)";
      }
      else if (/[Nna]/.test(placeholderChar)) {
        indexMap[reIndex++] = [placeholderChar, param && param.split(',')];
        return "([a-zA-Z\\u0080-\\u1fff]+)";
      }
      else if (/w/i.test(placeholderChar))
        return "[a-zA-Z\\u0080-\\u1fff]+";
      else if (/\s/.test(placeholderChar))
        return "\\s+";
      else
        return escapeRegExp(wholeMatch);
    }));

    if (!(match = parser.exec(date)))
      return undef;

    var ctorArgs = [0, 0, 0, 0, 0, 0,  0];
    for (var i = 1; i < reIndex; i++) {
      var matchVal = match[i];
      var indexEntry = indexMap[i];
      if (isList(indexEntry)) { // for a, n or N
        var placeholderChar = indexEntry[0];
        var mapEntry  = PARSE_DATE_MAP[placeholderChar];
        var ctorIndex = mapEntry[0];
        var valList = indexEntry[1] || mapEntry[1];
        var listValue = find(valList, function(v, index) { if (startsWith(matchVal.toLowerCase(), v.toLowerCase())) return index; });
        if (listValue == _null)
          return undef;
        if (placeholderChar == 'a')
          ctorArgs[ctorIndex] += listValue * 12;
        else
          ctorArgs[ctorIndex] = listValue;
      }
      else if (indexEntry) { // for numeric values (yHmMs)
        var value = parseFloat(matchVal);
        var mapEntry  = PARSE_DATE_MAP[indexEntry];
        if (isList(mapEntry))
          ctorArgs[mapEntry[0]] += value - mapEntry[1];
        else
          ctorArgs[mapEntry] += value;
      }
    }
    var d = new Date(ctorArgs[0], ctorArgs[1], ctorArgs[2], ctorArgs[3], ctorArgs[4], ctorArgs[5], ctorArgs[6]);
    return dateAdd(d, 'minutes', -getTimezone(timezoneOffsetMatch, 1, d) - getTimezone(match, timezoneIndex, d));
  }
571013
function dateFromArray(input, asUTC, hoursOffset, minutesOffset) {
        var i, date, forValid = [];
        for (i = 0; i < 7; i++) {
            forValid[i] = input[i] = (input[i] == null) ? (i === 2 ? 1 : 0) : input[i];
        }
        // we store whether we used utc or not in the input array
        input[7] = forValid[7] = asUTC;
        // if the parser flagged the input as invalid, we pass the value along
        if (input[8] != null) {
            forValid[8] = input[8];
        }
        // add the offsets to the time to be parsed so that we can have a clean array
        // for checking isValid
        input[3] += hoursOffset || 0;
        input[4] += minutesOffset || 0;
        date = new Date(0);
        if (asUTC) {
            date.setUTCFullYear(input[0], input[1], input[2]);
            date.setUTCHours(input[3], input[4], input[5], input[6]);
        } else {
            date.setFullYear(input[0], input[1], input[2]);
            date.setHours(input[3], input[4], input[5], input[6]);
        }
        date._a = forValid;
        return date;
    }
995704
def _parse_interval(value):
    
    try:
        return sorted(aniso8601.parse_interval(value))
    except ValueError:
        try:
            return aniso8601.parse_datetime(value), None
        except ValueError:
            return aniso8601.parse_date(value), None
886975
def _parse_date(self, date_info: dict) -> Extraction or None:
        

        user_defined_pattern = None

        if date_info['pattern']:
            user_defined_pattern = re.findall(r'%[a-zA-Z]', date_info['pattern'])

        miss_day = miss_month = miss_year = miss_week = True

        i = 0
        pattern = list()
        formatted = list()

        for s in date_info['groups']:
            if s:
                p = self._symbol_list[date_info['order']][i] if not user_defined_pattern else user_defined_pattern[i]
                if p in units['D']:
                    miss_day = False
                elif p in units['M']:
                    miss_month = False
                elif p in units['Y']:
                    miss_year = False
                elif p in units['W']:
                    miss_week = False
                formatted_str = s.strip('.').strip().lower()
                if p in ['%B', '%b', '%A', '%a']:
                    if formatted_str in foreign_to_english:
                        # TODO: rearrange language detection in a better way
                        if self._lan == 'en':
                            continue
                        formatted_str = foreign_to_english[formatted_str]
                if p in ['%b', '%a']:
                    formatted_str = formatted_str[:3]
                formatted.append(re.sub(r'[^0-9+\-]', '', formatted_str) if p == '%z' else formatted_str)
                pattern.append(p)
            i += 1

        # TODO: deduplicate in the regex extraction part would be better
        exist, new_formatted, new_pattern = set(), [], []
        for i in range(len(pattern)):
            if pattern[i] not in exist:
                if re.match(r'[a-zA-Z]', formatted[i]) and pattern[i] == '%a':
                    miss_week = True
                else:
                    new_pattern.append(pattern[i])
                    new_formatted.append(formatted[i])
                    exist.add(pattern[i])
        formatted, pattern = new_formatted, new_pattern

        if formatted and pattern:
            try:
                if self._settings[DATE_VALUE_RESOLUTION] == DateResolution.ORIGINAL:
                    self._settings[MIN_RESOLUTION] = DateResolutionHelper.min_resolution(pattern)
                date = datetime.datetime.strptime('-'.join(formatted), '-'.join(pattern))
            except ValueError:
                try:
                    date = datetime.datetime.strptime('-'.join(formatted[:-1]), '-'.join(pattern[:-1]))
                except ValueError:
                    warn('DateExtractor: Failed to parse string to datetime object. \n'
                         'Patterns are not matched with string or the formats are not supported. ' +
                         '-'.join(formatted) + ' with ' + '-'.join(pattern))
                    return None

            if miss_year and miss_month and miss_day:
                today = datetime.datetime.now()
                if miss_week:
                    date = date.replace(day=today.day, month=today.month, year=today.year)
                else:
                    date = today
                    week_of_day = formatted[0].strip().lower()
                    if week_of_day in foreign_to_english:
                        week_of_day = foreign_to_english[week_of_day]
                    target = day_of_week_to_number[week_of_day] if week_of_day in day_of_week_to_number \
                        else today.weekday()
                    if self._settings[PREFER_DATES_FROM] == 'past':
                        date = date + relativedelta(days=-(date.weekday()+7-target)%7)
                    elif self._settings[PREFER_DATES_FROM] == 'future':
                        date = date + relativedelta(days=(target+7-date.weekday())%7)
                    else:
                        delta = target - date.weekday()
                        if abs(delta) <= 3:
                            date = date + relativedelta(days=delta)
                        else:
                            date = date + relativedelta(days=delta-7)

            else:
                if miss_day:
                    last = calendar.monthrange(date.year, date.month)[1]
                    if self._settings[PREFER_DAY_OF_MONTH] == 'current':
                        cur = datetime.datetime.now().day
                        date = date.replace(day=cur if cur <= last else last)
                    elif self._settings[PREFER_DAY_OF_MONTH] == 'last':
                        date = date.replace(day=last)

                if miss_year:
                    today = datetime.datetime.now()
                    date = date.replace(year=today.year)
                    next_year = date.replace(year=today.year+1)
                    last_year = date.replace(year=today.year-1)
                    if self._settings[PREFER_DATES_FROM] == 'past':
                        date = last_year if date > today else date
                    elif self._settings[PREFER_DATES_FROM] == 'future':
                        date = next_year if date < today else date
                    else:
                        if date > today and (date-today > today-last_year):
                            date = last_year
                        elif date < today and (today-date > next_year-today):
                            date = next_year

            date = self._post_process_date(date)

            if date:
                return self._wrap_extraction(date, date_info['value'], date_info['start'], date_info['end'])
        return None
1008944
def parse_date(value):
    
    # Do the regex magic; also enforces 2 or 4 digit years
    match = Definitions.DATE_RE.match(value) if value else None
    if not match:
        return None
    # We're going to extract and prepare captured data in 'data'.
    data = {}
    captured = match.groupdict()
    fields = ['year', 'month', 'day', 'hour', 'minute', 'second']
    # If we matched on the RFC 1123 family format
    if captured['year']:
        for field in fields:
            data[field] = captured[field]
    # If we matched on the asctime format, use year2 etc.
    else:
        for field in fields:
            data[field] = captured[field + "2"]
    year = data['year']
    # Interpret lame 2-digit years - base the cutoff on UNIX epoch, in case
    # someone sets a '70' cookie meaning 'distant past'. This won't break for
    # 58 years and people who use 2-digit years are asking for it anyway.
    if len(year) == 2:
        if int(year) < 70:
            year = "20" + year
        else:
            year = "19" + year
    year = int(year)
    # Clamp to [1900, 9999]: strftime has min 1900, datetime has max 9999
    data['year'] = max(1900, min(year, 9999))
    # Other things which are numbers should convert to integer
    for field in ['day', 'hour', 'minute', 'second']:
        if data[field] is None:
            data[field] = 0
        data[field] = int(data[field])
    # Look up the number datetime needs for the named month
    data['month'] = Definitions.month_numbers[data['month'].lower()]
    return datetime.datetime(**data)
1200397
def rnd_date_array(size, start=date(1970, 1, 1), end=None, **kwargs):
    
    if end is None:
        end = date.today()
    start = parser.parse_date(start)
    end = parser.parse_date(end)
    _assert_correct_start_end(start, end)
    return _randn(size, _rnd_date, start, end)
315048
private static Data loadLeapSeconds() {
        Data bestData = null;
        URL url = null;
        try {
            // this is the new location of the file, working on Java 8, Java 9 class path and Java 9 module path
            Enumeration<URL> en = Thread.currentThread().getContextClassLoader().getResources("META-INF/" + LEAP_SECONDS_TXT);
            while (en.hasMoreElements()) {
                url = en.nextElement();
                Data candidate = loadLeapSeconds(url);
                if (bestData == null || candidate.getNewestDate() > bestData.getNewestDate()) {
                    bestData = candidate;
                }
            }
            // this location does not work on Java 9 module path because the resource is encapsulated
            en = Thread.currentThread().getContextClassLoader().getResources(LEAP_SECONDS_TXT);
            while (en.hasMoreElements()) {
                url = en.nextElement();
                Data candidate = loadLeapSeconds(url);
                if (bestData == null || candidate.getNewestDate() > bestData.getNewestDate()) {
                    bestData = candidate;
                }
            }
            // this location is the canonical one, and class-based loading works on Java 9 module path
            url = SystemUtcRules.class.getResource("/" + LEAP_SECONDS_TXT);
            if (url != null) {
                Data candidate = loadLeapSeconds(url);
                if (bestData == null || candidate.getNewestDate() > bestData.getNewestDate()) {
                    bestData = candidate;
                }
            }
        } catch (Exception ex) {
            throw new RuntimeException("Unable to load time-zone rule data: " + url, ex);
        }
        if (bestData == null) {
            // no data on classpath, but we allow manual registration of leap seconds
            // setup basic known data - MJD 1972-01-01 is 41317L, where offset was 10
            bestData = new Data(new long[] {41317L}, new int[] {10}, new long[] {tai(41317L, 10)});
        }
        return bestData;
    }
30577
def _strftime(pattern, time_struct=time.localtime()):
    
    try:
        return time.strftime(pattern, time_struct)
    except OSError:
        dt = datetime.datetime.fromtimestamp(_mktime(time_struct))
        # This is incredibly hacky and will probably break with leap
        # year overlaps and shit. Any complaints should go here:
        # https://support.microsoft.com/
        original = dt.year
        current = datetime.datetime.now().year
        dt = dt.replace(year=current)
        ts = dt.timestamp()
        if _isdst(dt):
            ts -= 3600
        string = time.strftime(pattern, time.localtime(ts))
        string = string.replace(str(current), str(original))
        return string