convert a named granularity into seconds.

    get value in seconds for named granularities: M1, M5 ... H1 etc.

    >>> print(granularity_to_time("M5"))
    300
13010
def granularity_to_time(s):
    
    mfact = {
        'S': 1,
        'M': 60,
        'H': 3600,
        'D': 86400,
        'W': 604800,
    }
    try:
        f, n = re.match("(?P<f>[SMHDW])(?:(?P<n>\d+)|)", s).groups()
        n = n if n else 1
        return mfact[f] * int(n)

    except Exception as e:
        raise ValueError(e)
1314999
def timeit(self, metric, func, *args, **kwargs):
        
        (res, seconds) = timeit(func, *args, **kwargs)
        self.timing(metric, seconds * 1000.0)
        return res
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
1132447
def to_native(self):
        
        h, m, s = self.hour_minute_second
        s, ns = nano_divmod(s, 1)
        ms = int(nano_mul(ns, 1000000))
        return time(h, m, s, ms)
179078
def from_time(cls, other):
        
        return cls(other.hour, other.minute, other.second, other.microsecond)
1203858
def human_duration(duration_seconds: float) -> str:
    """"""
    if duration_seconds < 0.001:
        return '0 ms'
    if duration_seconds < 1:
        return '{} ms'.format(int(duration_seconds * 1000))
    return '{} s'.format(int(duration_seconds))
301123
def convert_timedelta_type(obj):
    ''' 

    '''
    if isinstance(obj, dt.timedelta):
        return obj.total_seconds() * 1000.
    elif isinstance(obj, np.timedelta64):
        return (obj / NP_MS_DELTA)
621163
def SecondsToZuluTS(secs=None):
	

	if not secs:  secs = int(time.time())

	return(datetime.utcfromtimestamp(secs).strftime("%Y-%m-%dT%H:%M:%SZ"))
761301
def datetime_to_ms(dt):
    
    seconds = calendar.timegm(dt.utctimetuple())
    return seconds * 1000 + int(dt.microsecond / 1000)
860936
def humanize_seconds(total_seconds,
                     frmt='{hours:02d}:{minutes:02d}:{seconds:02d}',
                     negative_frmt=None):
    
    if negative_frmt is None:
        negative_frmt = '<span class="negative-time">-{0}</span>'.format(frmt)
    seconds = abs(int(total_seconds))
    mapping = {
        'hours': seconds // 3600,
        'minutes': seconds % 3600 // 60,
        'seconds': seconds % 3600 % 60,
    }
    if total_seconds < 0:
        result = negative_frmt.format(**mapping)
    else:
        result = frmt.format(**mapping)
    return mark_safe(result)
1206163
def _total_seconds(t):
    '''
    
    '''
    return sum([
        int(t.days * 86400 + t.seconds),
        int(round(t.microseconds / 1000000.0))
    ])
665745
def time2seconds(t):
    """"""
    return t.hour * 3600 + t.minute * 60 + t.second + float(t.microsecond) / 1e6
6379
def s_from_dhms(time):
    """"""
    dhms_s = { 's' : 1, 'm' : 60, 'h' : 3600, 'd' : 86400 }
    time = time.lower()
    word_list = re.findall('\d*[^\d]*',time)
    seconds=0 
    for word in word_list:
        if word != '':
            sec = 1
            for t in list(dhms_s.keys()):
                nw = word.replace(t,'')
                if nw != word:
                    sec = dhms_s[t]
                    word = nw
                    break
            try:
                seconds += int(word) * sec
            except:
                raise RuntimeError('unknown format in timestring ' + time)
    return seconds
189528
def seconds_to_str_fromatter(_format):
    
    # check directives are correct 
    
    if _format == "%S":
        def _fromatter(seconds):
            return "{:.2f}".format(seconds)
    
    elif _format == "%I":
        def _fromatter(seconds):
            return "{0}".format(int(seconds * 1000))
    
    else:
        _format = _format.replace("%h", "{hrs:02d}")
        _format = _format.replace("%m", "{mins:02d}")
        _format = _format.replace("%s", "{secs:02d}")
        _format = _format.replace("%i", "{millis:03d}")
        
        try:
            i = _format.index("%")
            raise TimeFormatError("Unknow time format directive '{0}'".format(_format[i:i+2]))
        except ValueError:
            pass
        
        def _fromatter(seconds):
            millis = int(seconds * 1000)
            hrs, millis = divmod(millis, 3600000)
            mins, millis = divmod(millis, 60000)
            secs, millis = divmod(millis, 1000)
            return _format.format(hrs=hrs, mins=mins, secs=secs, millis=millis)
    
    return _fromatter
860919
def grok_seconds(lease):
    """"""
    if lease.endswith('s'):
        return int(lease[0:-1])
    elif lease.endswith('m'):
        return int(lease[0:-1]) * 60
    elif lease.endswith('h'):
        return int(lease[0:-1]) * 3600

    return None
959258
def time_to_number(self, time):
        
        if not isinstance(time, datetime.time):
            raise TypeError(time)
        return ((time.second / 60.0 + time.minute) / 60.0 + time.hour) / 24.0
48904
def stringify_seconds(seconds=0):
    
    seconds = int(seconds)
    minutes = seconds / 60
    ti = {'h': 0, 'm': 0, 's': 0}

    if seconds > 0:
        ti['s'] = seconds % 60
        ti['m'] = minutes % 60
        ti['h'] = minutes / 60

    return "%dh %dm %ds" % (ti['h'], ti['m'], ti['s'])