Parse text and return a time in seconds.

    The text is of the format 0h : 0.min:0.0s:0 ms:0us:0 ns.
    Spaces are not taken into account and any of the specifiers can be ignored.
185594
def gettime_s(text):
    
    pattern = r'([+-]?\d+\.?\d*) ?([munsecinh]+)'
    matches = re.findall(pattern, text)
    if len(matches) == 0:
        return None
    time = 0.
    for res in matches:
        tmp = float(res[0])
        if res[1] == 'ns':
            tmp *= 1e-9
        elif res[1] == 'us':
            tmp *= 1e-6
        elif res[1] == 'ms':
            tmp *= 1e-3
        elif res[1] == 'min':
            tmp *= 60
        elif res[1] == 'h':
            tmp *= 3600
        time += tmp
    return time
898743
def _parse_time(self, raw_value):
        ""
        n = bytes_to_bint(raw_value)
        s = n // 10000
        m = s // 60
        h = m // 60
        m = m % 60
        s = s % 60
        return (h, m, s, (n % 10000) * 100)
278958
def parse_string(str)
      hms = DURATION_REGEXP.match(str)
      raise ArgumentError, "The duration #{str} does not match the expected format #{DURATION_REGEXP}" if hms.nil?
      hms.captures[0].to_i * 60 * 60 + hms.captures[1].to_i * 60 + hms.captures[2].to_i
    end
1015415
def parse_data(data)
      case data
      when Numeric
        @sec, @ms  = data.divmod(1000)
        @min, @sec = @sec.divmod(60)
        @hrs, @min = @min.divmod(60)
      when String
        time, float = data.split(/\.|\,/)
        time = time.split(/:/).map(&:to_i)
        @ms =  (('0.%d' % float.to_i).to_f * 1000).to_i if float
        @sec, @min, @hrs = time.reverse
      else fail 'Format unknown.'
      end
      # FIXME: dunno what to do about this.. nil = problems with to_i
      @hrs ||= 0; @min ||= 0; @sec ||= 0;  @ms ||= 0
    end
1204019
def human_time(seconds):
	''' 
	'''
	isec = int(seconds)
	s = isec % 60
	m = isec // 60 % 60
	h = isec // 60 // 60 % 24
	d = isec // 60 // 60 // 24 % 7
	w = isec // 60 // 60 // 24 // 7

	result = ''
	for t in [ ('W', w), ('D', d), ('h', h), ('m', m), ('s', s) ]:
		if t[1]:
			result += str(t[1]) + t[0]

	return result
1260464
def parse_input(self, text):
        

        parts = util.split(text)
        command = parts[0] if text and parts else None
        command = command.lower() if command else None
        args = parts[1:] if len(parts) > 1 else []

        return (command, args)
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]
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()
31936
def seconds2str(seconds):
    """"""

    if seconds < 0:
        return "{0:.3g}s".format(seconds)
    elif math.isnan(seconds):
        return "NaN"
    elif math.isinf(seconds):
        return "Inf"

    m, s = divmod(seconds, 60)
    h, m = divmod(m, 60)
    if h >= 1:
        return "{0:g}h {1:02g}m {2:.3g}s".format(h, m, s)
    elif m >= 1:
        return "{0:02g}m {1:.3g}s".format(m, s)
    else:
        return "{0:.3g}s".format(s)
1205018
def pprint(self, seconds):
        
        return ("%d:%02d:%02d.%03d", reduce(lambda ll, b: divmod(ll[0], b) + ll[1:], [(seconds * 1000,), 1000, 60, 60]))
689401
def parse(text, base=None, chop=False):
    '''
    
    '''
    #TODO: use base to facilitate relative time offsets
    text = text.strip().lower()
    text = (''.join([c for c in text if c.isdigit()]))

    if chop:
        text = text[:17]

    # TODO: support relative time offsets here...

    tlen = len(text)
    if tlen == 4:
        dt = datetime.datetime.strptime(text, '%Y')

    elif tlen == 6:
        dt = datetime.datetime.strptime(text, '%Y%m')

    elif tlen == 8:
        dt = datetime.datetime.strptime(text, '%Y%m%d')

    elif tlen == 10:
        dt = datetime.datetime.strptime(text, '%Y%m%d%H')

    elif tlen == 12:
        dt = datetime.datetime.strptime(text, '%Y%m%d%H%M')

    elif tlen == 14:
        dt = datetime.datetime.strptime(text, '%Y%m%d%H%M%S')

    elif tlen in (15, 16, 17):
        dt = datetime.datetime.strptime(text, '%Y%m%d%H%M%S%f')

    else:
        raise s_exc.BadTypeValu(valu=text, name='time',
                                mesg='Unknown time format')

    epoch = datetime.datetime(1970, 1, 1)
    return int((dt - epoch).total_seconds() * 1000)
635025
def parse_profile_date(text, suppress=False):
  
  try:
    if text == u"Unknown" or text == u"?" or text == u"Not available":
      return None
    if text == u"Now":
      return datetime.datetime.now()

    seconds_match = re.match(r'(?P<seconds>[0-9]+) second(s)? ago', text)
    if seconds_match:
      return datetime.datetime.now() - datetime.timedelta(seconds=int(seconds_match.group(u'seconds')))

    minutes_match = re.match(r'(?P<minutes>[0-9]+) minute(s)? ago', text)
    if minutes_match:
      return datetime.datetime.now() - datetime.timedelta(minutes=int(minutes_match.group(u'minutes')))

    hours_match = re.match(r'(?P<hours>[0-9]+) hour(s)? ago', text)
    if hours_match:
      return datetime.datetime.now() - datetime.timedelta(hours=int(hours_match.group(u'hours')))

    today_match = re.match(r'Today, (?P<hour>[0-9]+):(?P<minute>[0-9]+) (?P<am>[APM]+)', text)
    if today_match:
      hour = int(today_match.group(u'hour'))
      minute = int(today_match.group(u'minute'))
      am = today_match.group(u'am')
      if am == u'PM' and hour < 12:
        hour += 12
      today = datetime.date.today()
      return datetime.datetime(year=today.year, month=today.month, day=today.day, hour=hour, minute=minute, second=0)

    yesterday_match = re.match(r'Yesterday, (?P<hour>[0-9]+):(?P<minute>[0-9]+) (?P<am>[APM]+)', text)
    if yesterday_match:
      hour = int(yesterday_match.group(u'hour'))
      minute = int(yesterday_match.group(u'minute'))
      am = yesterday_match.group(u'am')
      if am == u'PM' and hour < 12:
        hour += 12
      yesterday = datetime.date.today() - datetime.timedelta(days=1)
      return datetime.datetime(year=yesterday.year, month=yesterday.month, day=yesterday.day, hour=hour, minute=minute, second=0)

    try:
      return datetime.datetime.strptime(text, '%m-%d-%y, %I:%M %p')
    except ValueError:
      pass
    # see if it's a date.
    try:
      return datetime.datetime.strptime(text, '%m-%d-%y').date()
    except ValueError:
      pass
    try:
      return datetime.datetime.strptime(text, '%Y-%m-%d').date()
    except ValueError:
      pass
    try:
      return datetime.datetime.strptime(text, '%Y-%m-00').date()
    except ValueError:
      pass
    try:
      return datetime.datetime.strptime(text, '%Y-00-00').date()
    except ValueError:
      pass
    try:
      return datetime.datetime.strptime(text, '%B %d, %Y').date()
    except ValueError:
      pass
    try:
      return datetime.datetime.strptime(text, '%b %d, %Y').date()
    except ValueError:
      pass
    try:
      return datetime.datetime.strptime(text, '%Y').date()
    except ValueError:
      pass
    try:
      return datetime.datetime.strptime(text, '%b %d, %Y').date()
    except ValueError:
      pass
    # see if it's a month/year pairing.
    return datetime.datetime.strptime(text, '%b %Y').date()
  except:
    if suppress:
      return None
    raise
218604
def in_a_while(days=0, seconds=0, microseconds=0, milliseconds=0,
               minutes=0, hours=0, weeks=0, time_format=TIME_FORMAT):
    
    if not time_format:
        time_format = TIME_FORMAT

    return time_in_a_while(days, seconds, microseconds, milliseconds,
                           minutes, hours, weeks).strftime(time_format)
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
34691
def read_time(self, content):
        
        if get_class_name(content) in self.content_type_supported:
            # Exit if readtime is already set
            if hasattr(content, 'readtime'):
                return None

            default_lang_conf = self.lang_settings['default']
            lang_conf = self.lang_settings.get(content.lang, default_lang_conf)
            avg_reading_wpm = lang_conf['wpm']

            num_words = len(content._content.split())
            # Floor division so we don't have to convert float -> int
            minutes = num_words // avg_reading_wpm
            # Get seconds to read, then subtract our minutes as seconds from
            # the time to get remainder seconds
            seconds = int((num_words / avg_reading_wpm * 60) - (minutes * 60))

            minutes_str = self.pluralize(
                minutes,
                lang_conf['min_singular'],
                lang_conf['min_plural']
            )

            seconds_str = self.pluralize(
                seconds,
                lang_conf['sec_singular'],
                lang_conf['sec_plural']
            )

            content.readtime = minutes
            content.readtime_string = minutes_str
            content.readtime_with_seconds = (minutes, seconds,)
            content.readtime_string_with_seconds = "{}, {}".format(
                minutes_str, seconds_str)
573024
def _decode_time(self, text):
        """"""

        if self._kp.version >= (4, 0):
            # decode KDBX4 date from b64 format
            try:
                return (
                    datetime(year=1, month=1, day=1, tzinfo=tz.gettz('UTC')) +
                    timedelta(
                        seconds = struct.unpack('<Q', base64.b64decode(text))[0]
                    )
                )
            except BinasciiError:
                return parser.parse(
                    text,
                    tzinfos={'UTC':tz.gettz('UTC')}
                )
        else:
            return parser.parse(
                text,
                tzinfos={'UTC':tz.gettz('UTC')}
            )
15606
def parse_time(time_input):
    
    if isinstance(time_input, datetime.date):
        return time_input.isoformat()  # datetime.date only returns date, datetime.datetime also returns time

    if len(time_input) < 8:
        raise ValueError('Invalid time string {}.\n'
                         'Please specify time in formats YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS'.format(time_input))
    time = dateutil.parser.parse(time_input)
    if len(time_input) <= 10:
        return time.date().isoformat()
    return time.isoformat()