An argparse type representing a timespan such as 6h for 6 hours.
173463
def timespan_type(arg):
	""""""
	try:
		arg = parse_timespan(arg)
	except ValueError:
		raise argparse.ArgumentTypeError("{0} is not a valid time span".format(repr(arg)))
	return arg
364534
def _date_time_match(cron, **kwargs):
    '''
    
    '''
    return all([kwargs.get(x) is None or cron[x] == six.text_type(kwargs[x])
                or (six.text_type(kwargs[x]).lower() == 'random' and cron[x] != '*')
                for x in ('minute', 'hour', 'daymonth', 'month', 'dayweek')])
855241
def _ts_parse(ts):
    """"""
    dt = datetime.strptime(ts[:19],"%Y-%m-%dT%H:%M:%S")
    if ts[19] == '+':
        dt -= timedelta(hours=int(ts[20:22]),minutes=int(ts[23:]))
    elif ts[19] == '-':
        dt += timedelta(hours=int(ts[20:22]),minutes=int(ts[23:]))
    return dt.replace(tzinfo=pytz.UTC)
1290997
def _StrftimeLocal(value, unused_context, args):
    
    time_tuple = time.localtime(value)
    return _StrftimeHelper(args, time_tuple)
265926
def toc(*args, **kwargs):
    
    global Gtic_start
    f_elapsedTime = time.time() - Gtic_start
    for key, value in kwargs.items():
        if key == 'sysprint':   return value % f_elapsedTime
        if key == 'default':    return "Elapsed time = %f seconds." % f_elapsedTime
    return f_elapsedTime
809003
def _datetime_to_date(arg):
    
    _arg = parse(arg)
    if isinstance(_arg, datetime.datetime):
        _arg = _arg.date()
    return _arg
1002974
def human_time(timespan, precision=3):
    """"""

    if timespan >= 60.0:
        # Format time greater than one minute in a human-readable format
        # Idea from http://snipplr.com/view/5713/
        def _format_long_time(time):
            suffixes = ('d', 'h', 'm', 's')
            lengths = (24*60*60, 60*60, 60, 1)

            for suffix, length in zip(suffixes, lengths):
                value = int(time / length)

                if value > 0:
                    time %= length
                    yield '%i%s' % (value, suffix)

                if time < 1:
                    break

        return ' '.join(_format_long_time(timespan))

    else:
        units = ['s', 'ms', 'us', 'ns']

        # Attempt to replace 'us' with 'µs' if UTF-8 encoding has been set
        if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding == 'UTF-8':
            try:
                units[2] = b'\xc2\xb5s'.decode('utf-8')
            except UnicodeEncodeError:
                pass

        scale = [1.0, 1e3, 1e6, 1e9]

        if timespan > 0.0:
            # Determine scale of timespan (s = 0, ms = 1, µs = 2, ns = 3)
            order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
        else:
            order = 3

        return '%.*g %s' % (precision, timespan * scale[order], units[order])
1113331
def cmd_time(self, args):
        ''''''
        tusec = self.master.field('SYSTEM_TIME', 'time_unix_usec', 0)
        if tusec == 0:
            print("No SYSTEM_TIME time available")
            return
        print("%s (%s)\n" % (time.ctime(tusec * 1.0e-6), time.ctime()))
631385
def timing(rounds=1, limit=None):
    '''
    
    '''
    def decorator(method):
        @functools.wraps(method)
        def f():
            if rounds == 1:
                start = time.time()
                method()
                duration = time.time() - start
            else:
                start = time.time()
                for i in range(rounds):
                    method()
                duration = (time.time() - start) / rounds
            # Use milliseconds for duration counter
            duration = duration * 1e3

            print('Test "%s.%s" took %.06f ms.' % (method.__module__, method.__name__, duration))
            if limit is not None:
                assert limit > duration, 'Timing failure: %.06f > %.06f' % (duration, limit)

        # Run tests with timings, only if WITH_TIMINGS environment variable is set.
        # This is because tests with multiple rounds can take long to process.
        if environ.get('WITH_TIMINGS', None) == '1':
            return f
        return method
    return decorator
1269645
def unixtime(cdf_time, to_np=False):  # @NoSelf
        
        import datetime
        time_list = CDFepoch.breakdown(cdf_time, to_np=False)

        #Check if only one time was input into unixtime.
        #If so, turn the output of breakdown into a list for this function to work
        if hasattr(cdf_time, '__len__'):
           if len(cdf_time) == 1:
               time_list = [time_list]
        else:
            time_list = [time_list]

        unixtime = []
        for t in time_list:
            date = ['year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond']
            for i in range(0, len(t)):
                if i > 7:
                    continue
                elif i == 6:
                    date[i] = 1000*t[i]
                elif i == 7:
                    date[i-1] += t[i]
                else:
                    date[i] = t[i]
            unixtime.append(datetime.datetime(*date).replace(tzinfo=datetime.timezone.utc).timestamp())
        return np.array(unixtime) if to_np else unixtime
319894
def at(self, time_str):
        
        assert self.unit in ('days', 'hours') or self.start_day
        hour, minute = time_str.split(':')
        minute = int(minute)
        if self.unit == 'days' or self.start_day:
            hour = int(hour)
            assert 0 <= hour <= 23
        elif self.unit == 'hours':
            hour = 0
        assert 0 <= minute <= 59
        self.at_time = datetime.time(hour, minute)
        return self
1229700
def nsamples_to_hourmin(x, pos):
    '''
    '''

    h, m, s = hourminsec(x/16.0)
    return '{:.0f}h {:2.0f}′'.format(h, m+round(s))
1200666
def main(args=None):
    
    # define command line arguments
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("-V", "--version", action="version",
                        version=__version__,
                        help="show version number and exit")
    parser.add_argument("-l", "--local", action="store_true", default=False,
                        help="print datetimes in local timezone")
    parser.add_argument("-f", "--format", type=str, action="store",
                        default=r"%Y-%m-%d %H:%M:%S.%f %Z",
                        help="output datetime format (default: %(default)r)")
    parser.add_argument("input", help="GPS or datetime string to convert",
                        nargs="*")

    # parse and convert
    args = parser.parse_args(args)
    input_ = " ".join(args.input)
    output = tconvert(input_)

    # print (now with timezones!)
    if isinstance(output, datetime.datetime):
        output = output.replace(tzinfo=tz.tzutc())
        if args.local:
            output = output.astimezone(tz.tzlocal())
        print(output.strftime(args.format))
    else:
        print(output)
242351
def args_as_tuple(self):
        """"""
        result = ("currentdate", )
        result += (
            ":zone",
            self.extra_arguments["zone"].strip('"'),
            self.arguments["match-type"],
        )
        if self.arguments["match-type"] in [":count", ":value"]:
            result += (self.extra_arguments["match-type"].strip('"'), )
        result += (self.arguments["date-part"].strip('"'), )
        value = self.arguments["key-list"]
        if isinstance(value, list):
            # FIXME
            value = "[{}]".format(
                ",".join('"{}"'.format(item) for item in value))
        if value.startswith("["):
            result = result + tuple(tools.to_list(value))
        else:
            result = result + (value.strip('"'),)
        return result
645088
def to_datetime(value):
    """"""
    if value is None:
        return None

    if isinstance(value, six.integer_types):
        return parser.parse(value)
    return parser.isoparse(value)
528219
def load_dostime(buf, pos):
    """"""
    stamp, pos = load_le32(buf, pos)
    tup = parse_dos_time(stamp)
    return to_datetime(tup), pos
1021608
def uptime():
    """"""
    from datetime import timedelta

    with open('/proc/uptime', 'r') as f:
        uptime_seconds = float(f.readline().split()[0])
        uptime_string = str(timedelta(seconds=uptime_seconds))

    bob.says(uptime_string)