P1D to (1, ("DAYS", isodate.Duration(days=1)).
    P1Y to (1, ("YEARS", isodate.Duration(years=1)).
    :param time_gap: ISO8601 string.
    :return: tuple with quantity and unit of time.
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)
1347953
def to_seconds(base = nil)
      valid_base?(base)
      return factor(base) * atom if base.nil?
      target = ::Time.new(base.year + atom.to_i, base.month, base.day, base.hour, base.minute, base.second, base.zone)

      target - base.to_time
    end
209366
def dt2decyear(dt):
    
    year = dt.year
    startOfThisYear = datetime(year=year, month=1, day=1)
    startOfNextYear = datetime(year=year+1, month=1, day=1)
    yearElapsed = sinceEpoch(dt) - sinceEpoch(startOfThisYear)
    yearDuration = sinceEpoch(startOfNextYear) - sinceEpoch(startOfThisYear)
    fraction = yearElapsed/yearDuration
    return year + fraction
1147791
def get_duration(timestr1, timestr2, units='s'):
    
    valid_units = ['s', 'min', 'h']
    assert units in valid_units,\
      "Units must be one of {!s}".format(valid_units)

    duration = (
        gt.timestr_to_seconds(timestr2) - gt.timestr_to_seconds(timestr1)
    )

    if units == 's':
        return duration
    elif units == 'min':
        return duration/60
    else:
        return duration/3600
220680
def timesince(self, when):
        
        units = (
            ("year",   60 * 60 * 24 * 365),
            ("week",   60 * 60 * 24 * 7),
            ("day",    60 * 60 * 24),
            ("hour",   60 * 60),
            ("minute", 60),
            ("second", 1),
        )
        delta = datetime.now() - when
        total_seconds = delta.days * 60 * 60 * 24 + delta.seconds
        parts = []
        for name, seconds in units:
            value = total_seconds / seconds
            if value > 0:
                total_seconds %= seconds
                s = "s" if value != 1 else ""
                parts.append("%s %s%s" % (value, name, s))
        return " and ".join(", ".join(parts).rsplit(", ", 1))
268505
def date2doy(time: Union[str, datetime.datetime]) -> Tuple[int, int]:
    

    T = np.atleast_1d(time)

    year = np.empty(T.size, dtype=int)
    doy = np.empty_like(year)

    for i, t in enumerate(T):
        yd = str(datetime2yeardoy(t)[0])

        year[i] = int(yd[:4])
        doy[i] = int(yd[4:])

    assert ((0 < doy) & (doy < 366)).all(), 'day of year must be 0 < doy < 366'

    return doy, year
1022437
def convert_time_units(t):
    
    if t == 0:
        return '0 s'
    order = log10(t)
    if -9 < order < -6:
        time_units = 'ns'
        factor = 1000000000
    elif -6 <= order < -3:
        time_units = 'us'
        factor = 1000000
    elif -3 <= order < -1:
        time_units = 'ms'
        factor = 1000.
    elif -1 <= order:
        time_units = 's'
        factor = 1
    return "{:.3f} {}".format(factor * t, time_units)
1212346
def _doy_to_datetimeindex(doy, epoch_year=2014):
    
    doy = np.atleast_1d(doy).astype('float')
    epoch = pd.Timestamp('{}-12-31'.format(epoch_year - 1))
    timestamps = [epoch + dt.timedelta(days=adoy) for adoy in doy]
    return pd.DatetimeIndex(timestamps)
1080390
def to_iso_date(self, dt):
        
        if dt is None:
            return ""
        if isinstance(dt, DateTime):
            return dt.ISO8601()
        if isinstance(dt, datetime):
            return dt.isoformat()
        raise TypeError("{} is neiter an instance of DateTime nor datetime"
                        .format(repr(dt)))
93613
def tai_timestamp():
    """"""
    timestamp = time.time()
    date = datetime.utcfromtimestamp(timestamp)
    if date.year < 1972:
        return timestamp
    offset = 10 + timestamp
    leap_seconds = [
        (1972, 1, 1),
        (1972, 7, 1),
        (1973, 1, 1),
        (1974, 1, 1),
        (1975, 1, 1),
        (1976, 1, 1),
        (1977, 1, 1),
        (1978, 1, 1),
        (1979, 1, 1),
        (1980, 1, 1),
        (1981, 7, 1),
        (1982, 7, 1),
        (1983, 7, 1),
        (1985, 7, 1),
        (1988, 1, 1),
        (1990, 1, 1),
        (1991, 1, 1),
        (1992, 7, 1),
        (1993, 7, 1),
        (1994, 7, 1),
        (1996, 1, 1),
        (1997, 7, 1),
        (1999, 1, 1),
        (2006, 1, 1),
        (2009, 1, 1),
        (2012, 7, 1),
        (2015, 7, 1),
        (2017, 1, 1),
    ]
    for idx, leap_date in enumerate(leap_seconds):
        if leap_date >= (date.year, date.month, date.day):
            return idx - 1 + offset
    return len(leap_seconds) - 1 + offset
225983
def yeardoy2datetime(yeardate: int,
                     utsec: Union[float, int] = None) -> datetime.datetime:
    
    if isinstance(yeardate, (tuple, list, np.ndarray)):
        if utsec is None:
            return np.asarray([yeardoy2datetime(y) for y in yeardate])
        elif isinstance(utsec, (tuple, list, np.ndarray)):
            return np.asarray([yeardoy2datetime(y, s) for y, s in zip(yeardate, utsec)])

    yeardate = int(yeardate)

    yd = str(yeardate)
    if len(yd) != 7:
        raise ValueError('yyyyddd expected')

    year = int(yd[:4])
    assert 0 < year < 3000, 'year not in expected format'

    dt = datetime.datetime(year, 1, 1) + datetime.timedelta(days=int(yd[4:]) - 1)
    assert isinstance(dt, datetime.datetime)

    if utsec is not None:
        dt += datetime.timedelta(seconds=utsec)

    return dt
543132
def CopyToDateTimeString(self):
    
    if self._timestamp is None:
      return None

    number_of_days, hours, minutes, seconds = self._GetTimeValues(
        int(self._timestamp))

    year, month, day_of_month = self._GetDateValuesWithEpoch(
        number_of_days, self._EPOCH)

    microseconds = int(
        (self._timestamp % 1) * definitions.MICROSECONDS_PER_SECOND)

    return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}.{6:06d}'.format(
        year, month, day_of_month, hours, minutes, seconds, microseconds)
1335817
def from_year(cls, year):
        

        first_day = date(year, 1, 1)
        return cls.from_date(first_day, period="year")
1372063
def duration_to_number(duration, units='seconds'):
    
    if isinstance(duration, (int, float, long)):
        return duration
    elif isinstance(duration, (datetime.timedelta,)):
        if units == 'seconds':
            return duration.total_seconds()
        else:
            msg = 'unit "%s" is not supported' % units
            raise NotImplementedError(msg)
    elif duration == inf or duration == -inf:
        msg = "Can't convert infinite duration to number"
        raise ValueError(msg)
    else:
        msg = 'duration is an unknown type (%s)' % duration
        raise TypeError(msg)
1277752
def from_date_time_string(cls, datetime_string, leap_year=False):
        
        dt = datetime.strptime(datetime_string, '%d %b %H:%M')
        return cls(dt.month, dt.day, dt.hour, dt.minute, leap_year)
803142
def ut1(self, year=None, month=1, day=1, hour=0, minute=0, second=0.0,
            jd=None):
        
        if jd is not None:
            ut1 = jd
        else:
            ut1 = julian_date(
                _to_array(year), _to_array(month), _to_array(day),
                _to_array(hour), _to_array(minute), _to_array(second),
            )
        return self.ut1_jd(ut1)
1199995
static public TimePeriod from(String quantityAndUnit) {
		String trimed = quantityAndUnit.trim();
		String allExceptLast = trimed.substring(0, trimed.length() - 1);
		if (StringUtils.isNumericSpace(allExceptLast)){ // short format
			long quantity = Long.parseLong(allExceptLast.trim());
			TimePeriodUnit unit = TimePeriodUnit.from(Character.toUpperCase(trimed.charAt(trimed.length() - 1)));
			return new TimePeriod(quantity, unit);
		}else{
			String[] durationAndUnit = StringUtils.split(trimed);
			Long duration = Long.valueOf(durationAndUnit[0]);
			TimePeriodUnit unit = TimePeriodUnit.from(durationAndUnit[1]);
			return new TimePeriod(duration, unit);
		}
	}