query
stringlengths 9
60
| language
stringclasses 1
value | code
stringlengths 105
25.7k
| url
stringlengths 91
217
|
---|---|---|---|
finding time elapsed using a timer
|
python
|
def elapsed_time_s(self):
"""
Return the amount of time that has elapsed since the timer was started.
Only works if the timer is active.
"""
if self._start_time:
return (datetime.datetime.now() - self._start_time).total_seconds()
else:
return 0
|
https://github.com/lobocv/anonymoususage/blob/847bdad0746ad1cc6c57fb9def201beb59fb8300/anonymoususage/tables/timer.py#L58-L66
|
finding time elapsed using a timer
|
python
|
def elapsed_time(self):
"""Get the elapsed time."""
# Timer is running
if self._t0 is not None:
return self._time + self._get_time()
else:
return self._time
|
https://github.com/fermiPy/fermipy/blob/9df5e7e3728307fd58c5bba36fd86783c39fbad4/fermipy/timing.py#L14-L21
|
finding time elapsed using a timer
|
python
|
def elapsed(self, total=True):
"""Return the elapsed time for the timer.
Parameters
----------
total : bool, optional (default True)
If ``True`` return the total elapsed time since the first
call of :meth:`start` for the selected timer, otherwise
return the elapsed time since the most recent call of
:meth:`start` for which there has not been a corresponding
call to :meth:`stop`.
Returns
-------
dlt : float
Elapsed time
"""
return self.timer.elapsed(self.label, total=total)
|
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/util.py#L1438-L1456
|
finding time elapsed using a timer
|
python
|
def elapsed_time(self):
"""
Return elapsed time as min:sec:ms. The .split separates out the
millisecond
"""
td = (datetime.datetime.now() - self.start_time)
sec = td.seconds
ms = int(td.microseconds / 1000)
return '{:02}:{:02}.{:03}'.format(sec % 3600 // 60, sec % 60, ms)
|
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/try/run_central_instances.py#L155-L164
|
finding time elapsed using a timer
|
python
|
def elapsed(self, label=None, total=True):
"""Get elapsed time since timer start.
Parameters
----------
label : string, optional (default None)
Specify the label of the timer for which the elapsed time is
required. If it is ``None``, the default timer with label
specified by the ``dfltlbl`` parameter of :meth:`__init__`
is selected.
total : bool, optional (default True)
If ``True`` return the total elapsed time since the first
call of :meth:`start` for the selected timer, otherwise
return the elapsed time since the most recent call of
:meth:`start` for which there has not been a corresponding
call to :meth:`stop`.
Returns
-------
dlt : float
Elapsed time
"""
# Get current time
t = timer()
# Default label is self.dfltlbl
if label is None:
label = self.dfltlbl
# Return 0.0 if default timer selected and it is not initialised
if label not in self.t0:
return 0.0
# Raise exception if timer with specified label does not exist
if label not in self.t0:
raise KeyError('Unrecognized timer key %s' % label)
# If total flag is True return sum of accumulated time from
# previous start/stop calls and current start call, otherwise
# return just the time since the current start call
te = 0.0
if self.t0[label] is not None:
te = t - self.t0[label]
if total:
te += self.td[label]
return te
|
https://github.com/bwohlberg/sporco/blob/8946a04331106f4e39904fbdf2dc7351900baa04/sporco/util.py#L1273-L1316
|
finding time elapsed using a timer
|
python
|
def elapsed(self):
"""
Return a timedelta representation of the time passed sine the worker
was running.
"""
if not self.start_date:
return None
return (self.end_date or datetime.utcnow()) - self.start_date
|
https://github.com/limpyd/redis-limpyd-jobs/blob/264c71029bad4377d6132bf8bb9c55c44f3b03a2/limpyd_jobs/workers.py#L354-L361
|
finding time elapsed using a timer
|
python
|
def elapsed(self):
"""
Get elapsed time is seconds (float)
"""
# Clock stops running when total is reached
if self.count == self.total:
elapsed = self.last_update - self.start
else:
elapsed = time.time() - self.start
return elapsed
|
https://github.com/Rockhopper-Technologies/enlighten/blob/857855f940e6c1bb84d0be849b999a18fff5bf5a/enlighten/_counter.py#L488-L499
|
finding time elapsed using a timer
|
python
|
def elapsed(self):
"""
Elapsed time [µs] between start and stop timestamps. If stop is empty then
returned time is difference between start and current timestamp.
"""
if self._stop is None:
return timer() - self._start
return self._stop - self._start
|
https://github.com/GPflow/GPflow/blob/549394f0b1b0696c7b521a065e49bdae6e7acf27/gpflow/actions.py#L56-L63
|
finding time elapsed using a timer
|
python
|
def elapsed(self):
"""Returns the number of seconds it has been since the start until the latest entry."""
if not self.started or self._start_time is None:
return 0.0
return self._timing_data[-1][0] - self._start_time
|
https://github.com/Robpol86/etaprogress/blob/224e8a248c2bf820bad218763281914ad3983fff/etaprogress/eta.py#L83-L87
|
finding time elapsed using a timer
|
python
|
def elapsed_ms(self):
""" Get the elapsed time in milliseconds. returns floating
point representation of elapsed time in seconds.
"""
dt = datetime.datetime.now() - self.start_time
return ((dt.days * 24 * 3600) + dt.seconds) * 1000 \
+ dt.microseconds / 1000.0
|
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/try/run_central_instances.py#L141-L147
|
finding time elapsed using a timer
|
python
|
def elapsed(t0=0.0):
"""get elapsed time from the give time
Returns:
now: the absolute time now
dt_str: elapsed time in string
"""
now = time()
dt = now - t0
dt_sec = Decimal(str(dt)).quantize(Decimal('.0001'), rounding=ROUND_DOWN)
if dt_sec <= 1:
dt_str = str(dt_sec) + ' second'
else:
dt_str = str(dt_sec) + ' seconds'
return now, dt_str
|
https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/utils/time.py#L5-L19
|
finding time elapsed using a timer
|
python
|
def elapsed_time(self) -> float:
"""
The number of seconds that has elapsed since the step started running
if the step is still running. Or, if the step has already finished
running, the amount of time that elapsed during the last execution of
the step.
"""
current_time = datetime.utcnow()
start = self.start_time or current_time
end = self.end_time or current_time
return (end - start).total_seconds()
|
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/projects/steps.py#L97-L107
|
finding time elapsed using a timer
|
python
|
def time(self, value):
""" Sets the time of the clock. Useful for seeking.
Parameters
----------
value : str or int
The time to seek to. Can be any of the following formats:
>>> 15.4 -> 15.4 # seconds
>>> (1,21.5) -> 81.5 # (min,sec)
>>> (1,1,2) -> 3662 # (hr, min, sec)
>>> '01:01:33.5' -> 3693.5 #(hr,min,sec)
>>> '01:01:33.045' -> 3693.045
>>> '01:01:33,5' #comma works too
"""
seconds = cvsecs(value)
self.reset()
self.previous_intervals.append(seconds)
|
https://github.com/dschreij/python-mediadecoder/blob/f01b02d790f2abc52d9792e43076cf4cb7d3ce51/mediadecoder/timer.py#L96-L113
|
finding time elapsed using a timer
|
python
|
def get(self):
""" Get the current timer value in seconds.
Returns: the elapsed time in seconds since the timer started or until the timer was stopped
"""
now = datetime.now()
if self._start_time:
if self._stop_time:
return (self._stop_time - self._start_time).total_seconds()
return (now - self._start_time).total_seconds()
return 0.
|
https://github.com/julienc91/utools/blob/6b2f18a5cb30a9349ba25a20c720c737f0683099/utools/dates.py#L71-L81
|
finding time elapsed using a timer
|
python
|
def check_timers(self):
""" Awake process if timer has expired """
if self._current is None:
# Advance the clocks. Go to future!!
advance = min([self.clocks] + [x for x in self.timers if x is not None]) + 1
logger.debug(f"Advancing the clock from {self.clocks} to {advance}")
self.clocks = advance
for procid in range(len(self.timers)):
if self.timers[procid] is not None:
if self.clocks > self.timers[procid]:
self.procs[procid].PC += self.procs[procid].instruction.size
self.awake(procid)
|
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/platforms/linux.py#L2262-L2273
|
finding time elapsed using a timer
|
python
|
def elapsed_time(self):
"""To know the duration of the function.
This property might return None if the function is still running.
"""
if self._end_time:
elapsed_time = round(self._end_time - self._start_time, 3)
return elapsed_time
else:
return None
|
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/profiling.py#L56-L65
|
finding time elapsed using a timer
|
python
|
def seconds(self):
"""
Returns the elapsed number of seconds that this timer has been running.
:return <int>
"""
seconds = self.elapsed().seconds
if self.limit() and self.countdown():
seconds = (self.limit() - self.elapsed().seconds)
return (seconds % 3600) % 60
|
https://github.com/bitesofcode/projexui/blob/f18a73bec84df90b034ca69b9deea118dbedfc4d/projexui/widgets/xtimerlabel.py#L175-L184
|
finding time elapsed using a timer
|
python
|
def get_time(self) -> float:
"""
Get the current time in seconds
Returns:
The current time in seconds
"""
if self.paused:
return self.pause_time
return self.player.get_time() / 1000.0
|
https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/timers/vlc.py#L53-L63
|
finding time elapsed using a timer
|
python
|
def timer_tick(self):
"""Callback executed every self.base_interval_msec to check timer
expirations.
"""
# TODO: should exceptions thrown from this be caught and ignored
self.process_timers()
delta = datetime.timedelta(milliseconds=self.base_interval_msec)
self._timeout = IOLoop.current().add_timeout(delta, self.timer_tick)
|
https://github.com/ejeschke/ginga/blob/a78c893ec6f37a837de851947e9bb4625c597915/ginga/web/jupyterw/JpHelp.py#L45-L53
|
finding time elapsed using a timer
|
python
|
def timer(func):
"""Time a method and print its duration after return
"""
name = func.__name__
@wraps(func)
def timed_func(self, *args, **kwargs): # pylint: disable=missing-docstring
_start = time.time()
out = func(self, *args, **kwargs)
self.log(2, '{0} took {1:.1f} sec'.format(name, time.time() - _start))
return out
return timed_func
|
https://github.com/gwpy/gwpy/blob/7a92b917e7dd2d99b15895293a1fa1d66cdb210a/gwpy/cli/cliproduct.py#L57-L69
|
finding time elapsed using a timer
|
python
|
def get_elapsed_timestamp(self) -> str:
"""
A human-readable version of the elapsed time for the last execution
of the step. The value is derived from the `ProjectStep.elapsed_time`
property.
"""
t = self.elapsed_time
minutes = int(t / 60)
seconds = int(t - (60 * minutes))
millis = int(100 * (t - int(t)))
return '{:>02d}:{:>02d}.{:<02d}'.format(minutes, seconds, millis)
|
https://github.com/sernst/cauldron/blob/4086aec9c038c402ea212c79fe8bd0d27104f9cf/cauldron/session/projects/steps.py#L109-L119
|
finding time elapsed using a timer
|
python
|
def _check_timers(self):
"""
Check for expired timers.
If there are any timers that expired, place them in the event
queue.
"""
if self._timer_queue:
timer = self._timer_queue[0]
if timer['timeout_abs'] < _current_time_millis():
# the timer is expired, remove first element in queue
self._timer_queue.pop(0)
# put into the event queue
self._logger.debug('Timer {} expired for stm {}, adding it to event queue.'.format(timer['id'], timer['stm'].id))
self._add_event(timer['id'], [], {}, timer['stm'], front=True)
# not necessary to set next timeout,
# complete check timers will be called again
else:
self._next_timeout = (
timer['timeout_abs'] - _current_time_millis()) / 1000
if self._next_timeout < 0:
self._next_timeout = 0
else:
self._next_timeout = None
|
https://github.com/falkr/stmpy/blob/78b016f7bf6fa7b6eba8dae58997fb99f7215bf7/stmpy/__init__.py#L344-L367
|
finding time elapsed using a timer
|
python
|
def timer(module, name, delta, duration_units='milliseconds'):
"""
Record a timing delta:
::
start_time_s = time.time()
do_some_operation()
end_time_s = time.time()
delta_s = end_time_s - start_time_s
delta_ms = delta_s * 1000
timer(__name__, 'my_timer', delta_ms)
"""
timer = get_metric('timers', module, name, Timer(duration_units))
timer.update(delta)
|
https://github.com/Yelp/uwsgi_metrics/blob/534966fd461ff711aecd1e3d4caaafdc23ac33f0/uwsgi_metrics/metrics.py#L179-L192
|
finding time elapsed using a timer
|
python
|
def get_sleep_timer(self):
"""Retrieves remaining sleep time, if any
Returns:
int or NoneType: Number of seconds left in timer. If there is no
sleep timer currently set it will return None.
"""
resp = self.avTransport.GetRemainingSleepTimerDuration([
('InstanceID', 0),
])
if resp['RemainingSleepTimerDuration']:
times = resp['RemainingSleepTimerDuration'].split(':')
return (int(times[0]) * 3600 +
int(times[1]) * 60 +
int(times[2]))
else:
return None
|
https://github.com/SoCo/SoCo/blob/671937e07d7973b78c0cbee153d4f3ad68ec48c6/soco/core.py#L1720-L1736
|
finding time elapsed using a timer
|
python
|
def elapsed(self):
"""
:return: duration in seconds spent in the context.
:rtype: float
"""
if self.end is None:
return self() - self.end
return self.end - self.start
|
https://github.com/BlueBrain/hpcbench/blob/192d0ec142b897157ec25f131d1ef28f84752592/hpcbench/toolbox/contextlib_ext.py#L80-L87
|
finding time elapsed using a timer
|
python
|
def get_elapsed_time(self):
"""Get the elapsed time of the current split.
"""
if self._start_time is None or self._end_time is not None:
# the stopwatch is paused
return self._elapsed_time
return self._elapsed_time + (datetime.datetime.now() - self._start_time)
|
https://github.com/ianlini/bistiming/blob/46a78ec647723c3516fc4fc73f2619ab41f647f2/bistiming/stopwatch.py#L104-L110
|
finding time elapsed using a timer
|
python
|
def print_total_timer():
"""
Print the content of the TotalTimer, if it's not empty. This function will automatically get
called when program exits.
"""
if len(_TOTAL_TIMER_DATA) == 0:
return
for k, v in six.iteritems(_TOTAL_TIMER_DATA):
logger.info("Total Time: {} -> {:.2f} sec, {} times, {:.3g} sec/time".format(
k, v.sum, v.count, v.average))
|
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/utils/timer.py#L65-L74
|
finding time elapsed using a timer
|
python
|
def timer(diff, processed):
"""Return the passed time."""
# Changes seconds into minutes and seconds
minutes, seconds = divmod(diff, 60)
try:
# Finds average time taken by requests
time_per_request = diff / float(len(processed))
except ZeroDivisionError:
time_per_request = 0
return minutes, seconds, time_per_request
|
https://github.com/s0md3v/Photon/blob/6a29f2c9782ea9b3dc090db1774a259033600e39/core/utils.py#L87-L96
|
finding time elapsed using a timer
|
python
|
def timeuntil(d, now=None):
"""
Like timesince, but returns a string measuring the time until
the given time.
"""
if not now:
if getattr(d, 'tzinfo', None):
now = datetime.datetime.now(LocalTimezone(d))
else:
now = datetime.datetime.now()
return timesince(now, d)
|
https://github.com/nikcub/floyd/blob/5772d0047efb11c9ce5f7d234a9da4576ce24edc/floyd/util/timesince.py#L59-L69
|
finding time elapsed using a timer
|
python
|
def _check_time_backwards(self):
"""Make sure a clock reset didn't cause time to go backwards
"""
now = time.time()
if now < self.start:
self.start = now
self.end = self.start + self.length
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/transport_plugins/awsiot/iotile_transport_awsiot/timeout.py#L27-L35
|
finding time elapsed using a timer
|
python
|
def get_time(self):
"""
:return: the machine's time
"""
command = const.CMD_GET_TIME
response_size = 1032
cmd_response = self.__send_command(command, b'', response_size)
if cmd_response.get('status'):
return self.__decode_time(self.__data[:4])
else:
raise ZKErrorResponse("can't get time")
|
https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L727-L737
|
finding time elapsed using a timer
|
python
|
def time_seconds(tc_array, year):
"""Return the time object from the timecodes
"""
tc_array = np.array(tc_array, copy=True)
word = tc_array[:, 0]
day = word >> 1
word = tc_array[:, 1].astype(np.uint64)
msecs = ((127) & word) * 1024
word = tc_array[:, 2]
msecs += word & 1023
msecs *= 1024
word = tc_array[:, 3]
msecs += word & 1023
return (np.datetime64(
str(year) + '-01-01T00:00:00Z', 's') +
msecs[:].astype('timedelta64[ms]') +
(day - 1)[:].astype('timedelta64[D]'))
|
https://github.com/pytroll/satpy/blob/1f21d20ac686b745fb0da9b4030d139893e066dd/satpy/readers/hrpt.py#L66-L82
|
finding time elapsed using a timer
|
python
|
def check_time(timer_id):
"""Add check points in a single line.
This method is suitable for running a task on a list of items. A timer will
be registered when the method is called for the first time.
:Example:
>>> import time
>>> import mmcv
>>> for i in range(1, 6):
>>> # simulate a code block
>>> time.sleep(i)
>>> mmcv.check_time('task1')
2.000
3.000
4.000
5.000
Args:
timer_id (str): Timer identifier.
"""
if timer_id not in _g_timers:
_g_timers[timer_id] = Timer()
return 0
else:
return _g_timers[timer_id].since_last_check()
|
https://github.com/open-mmlab/mmcv/blob/0d77f61450aab4dde8b8585a577cc496acb95d7f/mmcv/utils/timer.py#L91-L117
|
finding time elapsed using a timer
|
python
|
def elapsed(func):
"""A decorator for calculating time elapsed when execute function"""
@functools.wraps(func)
def wrapper(*args, **kw):
start = time.time()
print('Running `%s()` ...' % func.__name__)
res = func(*args, **kw)
end = time.time()
print('Function `%s()` running elapsed %.2f s' %
(func.__name__, end - start))
return res
return wrapper
|
https://github.com/zengbin93/zb/blob/ccdb384a0b5801b459933220efcb71972c2b89a7/zb/utils.py#L9-L22
|
finding time elapsed using a timer
|
python
|
def timer():
"""
Timer used for calculate time elapsed
"""
if sys.platform == "win32":
default_timer = time.clock
else:
default_timer = time.time
return default_timer()
|
https://github.com/CodersOfTheNight/oshino/blob/00f7e151e3ce1f3a7f43b353b695c4dba83c7f28/oshino/util.py#L20-L29
|
finding time elapsed using a timer
|
python
|
def expiration_time(self):
"""
Returns the time until this access attempt is forgotten.
"""
logging_forgotten_time = configuration.behavior.login_forgotten_seconds
if logging_forgotten_time <= 0:
return None
now = timezone.now()
delta = now - self.modified
time_remaining = logging_forgotten_time - delta.seconds
return time_remaining
|
https://github.com/django-py/django-doberman/blob/2e5959737a1b64234ed5a179c93f96a0de1c3e5c/doberman/models.py#L73-L86
|
finding time elapsed using a timer
|
python
|
def get_time_interval(start_time, end_time):
"""
获取两个unix时间戳之间的时间间隔
:param:
* start_time: (int) 开始时间,unix 时间戳
* end_time: (int) 结束时间,unix 时间戳
:return:
* interval_dict: (dict) 时间间隔字典
举例如下::
print('--- get_time_interval demo ---')
import time
start = int(time.time())
end = start - 98908
print(get_time_interval(end, start))
print('---')
执行结果::
--- get_time_interval demo ---
{'days': 1, 'hours': 3, 'minutes': 28, 'seconds': 28}
---
"""
if not isinstance(start_time, int) or not isinstance(end_time, int):
raise TypeError('start_time and end_time should be int, bu we got {0} and {1}'.
format(type(start_time), type(end_time)))
# 计算天数
time_diff = abs(end_time - start_time)
days = (time_diff // (60*60*24))
# 计算小时数
remain = time_diff % (60*60*24)
hours = (remain // (60*60))
# 计算分钟数
remain = remain % (60*60)
minutes = (remain // 60)
# 计算秒数
seconds = remain % 60
interval_dict = {"days": days, "hours": hours, "minutes": minutes, "seconds": seconds}
return interval_dict
|
https://github.com/chinapnr/fishbase/blob/23c5147a6bc0d8ed36409e55352ffb2c5b0edc82/fishbase/fish_date.py#L283-L329
|
finding time elapsed using a timer
|
python
|
def _find_weektime(datetime, time_type='min'):
"""
Finds the minutes/seconds aways from midnight between Sunday and Monday.
Parameters
----------
datetime : datetime
The date and time that needs to be converted.
time_type : 'min' or 'sec'
States whether the time difference should be specified in seconds or minutes.
"""
if time_type == 'sec':
return datetime.weekday() * 24 * 60 * 60 + datetime.hour * 60 * 60 + datetime.minute * 60 + datetime.second
elif time_type == 'min':
return datetime.weekday() * 24 * 60 + datetime.hour * 60 + datetime.minute
else:
raise ValueError("Invalid time type specified.")
|
https://github.com/yvesalexandre/bandicoot/blob/73a658f6f17331541cf0b1547028db9b70e8d58a/bandicoot/weekmatrix.py#L290-L307
|
finding time elapsed using a timer
|
python
|
def find_discrete(start_time, end_time, f, epsilon=EPSILON, num=12):
"""Find the times when a function changes value.
Searches between ``start_time`` and ``end_time``, which should both
be :class:`~skyfield.timelib.Time` objects, for the occasions where
the function ``f`` changes from one value to another. Use this to
search for events like sunrise or moon phases.
A tuple of two arrays is returned. The first array gives the times
at which the input function changes, and the second array specifies
the new value of the function at each corresponding time.
This is an expensive operation as it needs to repeatedly call the
function to narrow down the times that it changes. It continues
searching until it knows each time to at least an accuracy of
``epsilon`` Julian days. At each step, it creates an array of
``num`` new points between the lower and upper bound that it has
established for each transition. These two values can be changed to
tune the behavior of the search.
"""
ts = start_time.ts
jd0 = start_time.tt
jd1 = end_time.tt
if jd0 >= jd1:
raise ValueError('your start_time {0} is later than your end_time {1}'
.format(start_time, end_time))
periods = (jd1 - jd0) / f.rough_period
if periods < 1.0:
periods = 1.0
jd = linspace(jd0, jd1, periods * num // 1.0)
end_mask = linspace(0.0, 1.0, num)
start_mask = end_mask[::-1]
o = multiply.outer
while True:
t = ts.tt_jd(jd)
y = f(t)
indices = flatnonzero(diff(y))
if not len(indices):
return indices, y[0:0]
starts = jd.take(indices)
ends = jd.take(indices + 1)
# Since we start with equal intervals, they all should fall
# below epsilon at around the same time; so for efficiency we
# only test the first pair.
if ends[0] - starts[0] <= epsilon:
break
jd = o(starts, start_mask).flatten() + o(ends, end_mask).flatten()
return ts.tt_jd(ends), y.take(indices + 1)
|
https://github.com/skyfielders/python-skyfield/blob/51d9e042e06457f6b1f2415296d50a38cb3a300f/skyfield/almanac.py#L44-L101
|
finding time elapsed using a timer
|
python
|
def get_elapsed_time(self, issue):
"""
Gets the elapsed time since the last mark (either the updated time of the last log or the time that the issue was
marked in progress)
"""
last_mark = None
# Get the last mark from the work logs
worklogs = self.get_worklog(issue)
if worklogs:
last_worklog = worklogs[-1]
last_mark = dateutil.parser.parse(last_worklog.raw['updated'])
# If no worklogs, get the time since the issue was marked In Progress
if not last_mark:
last_mark = self.get_datetime_issue_in_progress(issue)
if last_mark:
now = datetime.datetime.now(dateutil.tz.tzlocal())
delta = now - last_mark
minutes = int(utils.timedelta_total_seconds(delta) / 60)
if minutes > 0:
return str(minutes) + 'm'
else:
return None
|
https://github.com/mapmyfitness/jtime/blob/402fb6b40ac7a78c23fd02fac50c6dbe49e5ebfd/jtime/jira_ext.py#L38-L62
|
finding time elapsed using a timer
|
python
|
def timeit(func):
"""
Returns the number of seconds that a function took along with the result
"""
@wraps(func)
def timer_wrapper(*args, **kwargs):
"""
Inner function that uses the Timer context object
"""
with Timer() as timer:
result = func(*args, **kwargs)
return result, timer
return timer_wrapper
|
https://github.com/romaryd/python-awesome-decorators/blob/8c83784149338ab69a25797e1097b214d33a5958/awesomedecorators/timez.py#L18-L33
|
finding time elapsed using a timer
|
python
|
def extract_time_info(text):
"""
Extract valid time(-range) information from a string according to our specs.
Args:
text (text_type): Raw string containing encoded time(-span) information.
Date/Time-combinations are expected in a ``YYYY-MM-DD hh:mm`` format.
Relative times can be given with ``-minutes``.
Please note that either *relative* or *absolute* times will be considered.
It is possible to either just specify a start date (as time, date,
or datetime) or a timerange (start and end). If a timerange is given
start and end need to be delimited exactly by ' - '.
Returns:
tuple: ``(timeframe, rest)`` tuple. Where ``timeframe`` is a tuple that
provides convinient access to all seperate elements extracted from
the raw string and ``rest`` is any substring stat has not been
matched to valid time/date info.
Note:
* Relative times always return just ``(None, None, None, None, timedelta)``.
"""
# [TODO] Add a list of supported formats.
def get_time(time, seconds=None):
"""Convert a times string representation to datetime.time instance."""
if time is None:
return time
if seconds:
time_format = '%H:%M:%S'
else:
time_format = '%H:%M'
return datetime.datetime.strptime(time.strip(), time_format).time()
def get_date(date):
"""Convert a dates string representation to datetime.date instance."""
if date:
date = datetime.datetime.strptime(date.strip(), "%Y-%m-%d").date()
return date
def date_time_from_groupdict(groupdict):
"""Return a date/time tuple by introspecting a passed dict."""
if groupdict['datetime']:
dt = parse_time(groupdict['datetime'])
time = dt.time()
date = dt.date()
else:
date = get_date(groupdict.get('date'))
time = get_time(groupdict.get('time'), groupdict.get('seconds'))
return (date, time)
# Baseline/default values.
result = {
'start_date': None,
'start_time': None,
'end_date': None,
'end_time': None,
'offset': None
}
rest = None
# Individual patterns for time/date substrings.
relative_pattern = '(?P<relative>-\d+)'
time_pattern = '(?P<time>\d{2}:\d{2}(?P<seconds>:\d{2})?)'
date_pattern = '(?P<date>\d{4}-\d{2}-\d{2})'
datetime_pattern = '(?P<datetime>\d{4}-\d{2}-\d{2} \d{2}:\d{2}(:\d{2})?)'
start = re.match('^({}|{}|{}|{}) (?P<rest>.+)'.format(relative_pattern, datetime_pattern,
date_pattern, time_pattern), text)
if start:
start_groups = start.groupdict()
if start_groups['relative']:
result['offset'] = datetime.timedelta(minutes=abs(int(start_groups['relative'])))
else:
date, time = date_time_from_groupdict(start_groups)
result['start_date'] = date
result['start_time'] = time
rest = start_groups['rest']
if rest:
end = re.match('^- ({}|{}|{}) (?P<rest>.+)'.format(datetime_pattern, date_pattern,
time_pattern), rest)
else:
end = None
if end and not start_groups['relative']:
end_groups = end.groupdict()
date, time = date_time_from_groupdict(end_groups)
result['end_date'] = date
result['end_time'] = time
rest = end_groups['rest']
result = TimeFrame(result['start_date'], result['start_time'], result['end_date'],
result['end_time'], result['offset'])
# Consider the whole string as 'rest' if no time/date info was extracted
if not rest:
rest = text
return (result, rest.strip())
|
https://github.com/projecthamster/hamster-lib/blob/bc34c822c239a6fa0cde3a4f90b0d00506fb5a4f/hamster_lib/helpers/time.py#L85-L186
|
finding time elapsed using a timer
|
python
|
def main(**kwargs):
"""
\b
Starts a countdown to or from TIME. Example values for TIME:
10, '1h 5m 30s', '12:00', '2020-01-01', '2020-01-01 14:00 UTC'.
\b
If TIME is not given, termdown will operate in stopwatch mode
and count forward.
\b
Hotkeys:
\tL\tLap (stopwatch mode only)
\tR\tReset
\tSPACE\tPause (will delay absolute TIME)
\tQ\tQuit
"""
if kwargs['time_format'] is None:
kwargs['time_format'] = \
DEFAULT_TIME_FORMAT[:-3] if kwargs['no_seconds'] else DEFAULT_TIME_FORMAT
if kwargs['timespec']:
curses.wrapper(countdown, **kwargs)
else:
seconds_elapsed, laps = curses.wrapper(stopwatch, **kwargs)
for lap_index, lap_time in enumerate(laps):
stderr.write("{:.3f}\t{}\tlap {}\n".format(
lap_time,
format_seconds(int(lap_time)),
lap_index + 1,
))
if laps:
stderr.write("{:.3f}\t{}\tlap {}\n".format(
seconds_elapsed,
format_seconds(int(seconds_elapsed)),
len(laps) + 1,
))
laps.append(seconds_elapsed)
total_seconds = sum(laps)
average_seconds = total_seconds / len(laps)
stderr.write("{:.3f}\t{}\tlap avg\n".format(
average_seconds,
format_seconds(int(average_seconds)),
))
stderr.write("{:.3f}\t{}\ttotal\n".format(
total_seconds,
format_seconds(int(total_seconds)),
))
else:
stderr.write("{:.3f}\t{}\ttotal\n".format(
seconds_elapsed,
format_seconds(int(seconds_elapsed)),
))
stderr.flush()
|
https://github.com/trehn/termdown/blob/aa0c4e39d9864fd1466ef9d76947fb93d0cf5be2/termdown.py#L681-L734
|
finding time elapsed using a timer
|
python
|
def timeit(func):
'''
计算运行消耗时间
@timeit
def test():
time.sleep(1)
'''
def wapper(*args, **kwargs):
_start = time.time()
retval = func(*args, **kwargs)
_end = time.time()
logger.info('function %s() used : %.6f s' % (func.__name__, _end - _start))
return retval
return wapper
|
https://github.com/vex1023/vxUtils/blob/58120a206cf96c4231d1e63d271c9d533d5f0a89/vxUtils/decorator.py#L77-L92
|
finding time elapsed using a timer
|
python
|
def time(self):
"""
Current value the time marker is pointing to
:rtype: float
"""
x, _, = self._canvas_ticks.coords(self._time_marker_image)
return self.get_position_time(x)
|
https://github.com/RedFantom/ttkwidgets/blob/02150322060f867b6e59a175522ef84b09168019/ttkwidgets/timeline.py#L978-L985
|
finding time elapsed using a timer
|
python
|
def set_time(self, value: float):
"""
Set the current time. This can be used to jump in the timeline.
Args:
value (float): The new time
"""
if value < 0:
value = 0
self.offset += self.get_time() - value
|
https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/timers/clock.py#L71-L81
|
finding time elapsed using a timer
|
python
|
def get_time(self) -> float:
"""
Get the current time in seconds
Returns:
The current time in seconds
"""
if self.pause_time is not None:
curr_time = self.pause_time - self.offset - self.start_time
return curr_time
curr_time = time.time()
return curr_time - self.start_time - self.offset
|
https://github.com/Contraz/demosys-py/blob/6466128a3029c4d09631420ccce73024025bd5b6/demosys/timers/clock.py#L57-L69
|
finding time elapsed using a timer
|
python
|
def timer(name, count):
'''Time this block.'''
start = time.time()
try:
yield count
finally:
duration = time.time() - start
print(name)
print('=' * 10)
print('Total: %s' % duration)
print(' Avg: %s' % (duration / count))
print(' Rate: %s' % (count / duration))
print('')
|
https://github.com/seomoz/reppy/blob/4cfa55894859a2eb2e656f191aeda5981c4df550/bench.py#L30-L42
|
finding time elapsed using a timer
|
python
|
def time_elapsed(func):
"""
记录函数运行耗时的生成器
:param func:
:return:
"""
@wraps(func)
def wrapper(*args, **kwargs):
timestamp = time.time() * 1000
ret = func(*args, **kwargs)
now_ts = time.time() * 1000
elapsed = now_ts - timestamp
print('%s costs time: %.2fms' % (func.__name__, elapsed))
return ret
return wrapper
|
https://github.com/restran/mountains/blob/a97fee568b112f4e10d878f815d0db3dd0a98d74/mountains/decorator/__init__.py#L49-L65
|
finding time elapsed using a timer
|
python
|
def _elapsed_time(begin_time, end_time):
"""Assuming format YYYY-MM-DD hh:mm:ss
Returns the elapsed time in seconds
"""
bt = _str2datetime(begin_time)
et = _str2datetime(end_time)
return float((et - bt).seconds)
|
https://github.com/pablorecio/Cobaya/blob/70b107dea5f31f51e7b6738da3c2a1df5b9f3f20/src/cobaya/hamster_task.py#L97-L106
|
finding time elapsed using a timer
|
python
|
def check_time(value):
"""check that it's a value like 03:45 or 1:1"""
try:
h, m = value.split(':')
h = int(h)
m = int(m)
if h >= 24 or h < 0:
raise ValueError
if m >= 60 or m < 0:
raise ValueError
except ValueError:
raise TimeDefinitionError("Invalid definition of time %r" % value)
|
https://github.com/mozilla/crontabber/blob/b510be349e71f165c1a9506db95bda0b88728f8b/crontabber/app.py#L640-L651
|
finding time elapsed using a timer
|
python
|
def get_timerange(self, start, end, code=None):
"""
获取某一段时间的某一只股票的指标
"""
try:
return self.data.loc[(slice(pd.Timestamp(start), pd.Timestamp(end)), slice(code)), :]
except:
return ValueError('CANNOT FOUND THIS TIME RANGE')
|
https://github.com/QUANTAXIS/QUANTAXIS/blob/bb1fe424e4108b62a1f712b81a05cf829297a5c0/QUANTAXIS/QAData/QAIndicatorStruct.py#L65-L72
|
finding time elapsed using a timer
|
python
|
def ttl(self, steps, relative_time=None):
'''
Return the ttl given the number of steps, None if steps is not defined
or we're otherwise unable to calculate one. If relative_time is defined,
then return a ttl that is the number of seconds from now that the
record should be expired.
'''
if steps:
if relative_time:
rtime = self.to_bucket(relative_time)
ntime = self.to_bucket(time.time())
# The relative time is beyond our TTL cutoff
if (ntime - rtime) > steps:
return 0
# The relative time is in "recent" past or future
else:
return (steps + rtime - ntime) * self._step
return steps * self._step
return None
|
https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/timeseries.py#L114-L133
|
finding time elapsed using a timer
|
python
|
def timeit(timer=None):
"""simple timer. returns a time object, or a string."""
if timer is None:
return time.time()
else:
took=time.time()-timer
if took<1:
return "%.02f ms"%(took*1000.0)
elif took<60:
return "%.02f s"%(took)
else:
return "%.02f min"%(took/60.0)
|
https://github.com/swharden/SWHLab/blob/a86c3c65323cec809a4bd4f81919644927094bf5/swhlab/common.py#L97-L108
|
finding time elapsed using a timer
|
python
|
def time(self):
"Return the time part, with tzinfo None."
return time(self.hour, self.minute, self.second, self.microsecond)
|
https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/datetime.py#L1550-L1552
|
finding time elapsed using a timer
|
python
|
def time_period(self):
"""
Time period that is determined from the arguments --date and --last. It's a 2-tuple with
(<start datetime>, <end_datetime>) items. An item is `None` if there isn't a limit.
"""
if self.args.time_period is None:
if self.args.files or is_pipe(STDIN_FILENO) or is_redirected(STDIN_FILENO):
time_period = (None, None)
else:
diff = 86400 # 24h = 86400 seconds
time_period = get_datetime_interval(int(time.time()), diff, 3600)
else:
time_period = self.args.time_period
logger.debug('time period to be processed: %r', time_period)
return time_period
|
https://github.com/brunato/lograptor/blob/b1f09fe1b429ed15110610092704ef12d253f3c9/lograptor/core.py#L318-L333
|
finding time elapsed using a timer
|
python
|
def get_time(self, idx=0):
"""Return the time of the tif data since the epoch
The time is stored in the "61238" tag.
"""
timestr = SingleTifPhasics._get_meta_data(path=self.path,
section="acquisition info",
name="date & heure")
if timestr is not None:
timestr = timestr.split(".")
# '2016-04-29_17h31m35s.00827'
structtime = time.strptime(timestr[0],
"%Y-%m-%d_%Hh%Mm%Ss")
fracsec = float(timestr[1]) * 1e-5
# use calendar, because we need UTC
thetime = calendar.timegm(structtime) + fracsec
else:
thetime = np.nan
return thetime
|
https://github.com/RI-imaging/qpformat/blob/364e29d7d9e8b9f1d7a4a25c753d1baf9d73d5eb/qpformat/file_formats/single_tif_phasics.py#L95-L113
|
finding time elapsed using a timer
|
python
|
def end_timing(self):
"""
Completes measuring time interval and updates counter.
"""
if self._callback != None:
elapsed = time.clock() * 1000 - self._start
self._callback.end_timing(self._counter, elapsed)
|
https://github.com/pip-services/pip-services-commons-python/blob/2205b18c45c60372966c62c1f23ac4fbc31e11b3/pip_services_commons/count/Timing.py#L37-L44
|
finding time elapsed using a timer
|
python
|
def unix_time(self, dt):
"""Returns the number of seconds since the UNIX epoch for the given
datetime (dt).
PARAMETERS:
dt -- datetime
"""
epoch = datetime.utcfromtimestamp(0)
delta = dt - epoch
return int(delta.total_seconds())
|
https://github.com/okpy/ok-client/blob/517f57dd76284af40ba9766e42d9222b644afd9c/client/protocols/unlock.py#L233-L242
|
finding time elapsed using a timer
|
python
|
def find_time(each_line,temp_func_list):
"""
calculate the approximate date/time from the timestamp about when the job
was built. This information was then saved in dict g_failed_test_info_dict.
In addition, it will delete this particular function handle off the temp_func_list
as we do not need to perform this action again.
Parameters
----------
each_line : str
contains a line read in from jenkins console
temp_func_list : list of Python function handles
contains a list of functions that we want to invoke to extract information from
the Jenkins console text.
:return: bool to determine if text mining should continue on the jenkins console text
"""
global g_weekdays
global g_months
global g_failed_test_info_dict
temp_strings = each_line.strip().split()
if (len(temp_strings) > 2):
if ((temp_strings[0] in g_weekdays) or (temp_strings[1] in g_weekdays)) and ((temp_strings[1] in g_months) or (temp_strings[2] in g_months)):
g_failed_test_info_dict["3.timestamp"] = each_line.strip()
temp_func_list.remove(find_time) # found timestamp, don't need to look again for it
return True
|
https://github.com/h2oai/h2o-3/blob/dd62aaa1e7f680a8b16ee14bc66b0fb5195c2ad8/scripts/logscrapedaily.py#L146-L175
|
finding time elapsed using a timer
|
python
|
def _GetTimeValue(self, name):
"""Retrieves a date and time value.
Args:
name (str): name of the date and time value, for example "atime" or
"mtime".
Returns:
dfdatetime.DateTimeValues: date and time value or None if not available.
"""
timestamp = getattr(self._tsk_file.info.meta, name, None)
if self._file_system_type in self._TSK_HAS_NANO_FS_TYPES:
name_fragment = '{0:s}_nano'.format(name)
fraction_of_second = getattr(
self._tsk_file.info.meta, name_fragment, None)
else:
fraction_of_second = None
return TSKTime(timestamp=timestamp, fraction_of_second=fraction_of_second)
|
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/tsk_file_entry.py#L650-L669
|
finding time elapsed using a timer
|
python
|
def countdown_timer(seconds=10):
"""Show a simple countdown progress bar
Parameters
----------
seconds
Period of time the progress bar takes to reach zero.
"""
tick = 0.1 # seconds
n_ticks = int(seconds / tick)
widgets = ['Pause for panic: ', progressbar.ETA(), ' ', progressbar.Bar()]
pbar = progressbar.ProgressBar(
widgets=widgets, max_value=n_ticks
).start()
for i in range(n_ticks):
pbar.update(i)
sleep(tick)
pbar.finish()
|
https://github.com/lsst-sqre/sqre-codekit/blob/98122404cd9065d4d1d570867fe518042669126c/codekit/progressbar.py#L19-L40
|
finding time elapsed using a timer
|
python
|
def time_in_a_while(days=0, seconds=0, microseconds=0, milliseconds=0,
minutes=0, hours=0, weeks=0):
"""
format of timedelta:
timedelta([days[, seconds[, microseconds[, milliseconds[,
minutes[, hours[, weeks]]]]]]])
:return: UTC time
"""
delta = timedelta(days, seconds, microseconds, milliseconds,
minutes, hours, weeks)
return datetime.utcnow() + delta
|
https://github.com/IdentityPython/pysaml2/blob/d3aa78eeb7d37c12688f783cb4db1c7263a14ad6/src/saml2/time_util.py#L173-L183
|
finding time elapsed using a timer
|
python
|
def countdown(self, interval: float = 0.5):
"""
Display a numeric countdown from 5
:param interval: The interval in seconds for each number.
"""
for c in '54321':
self.char_on(c)
time.sleep(interval * 0.66667)
self.all_off()
time.sleep(interval * 0.33333)
|
https://github.com/jayferg/faderport/blob/53152797f3dedd0fa56d66068313f5484e469a68/faderport.py#L305-L314
|
finding time elapsed using a timer
|
python
|
def time_enqueued(self):
"""Retrieve the timestamp at which the task was enqueued.
See: https://cloud.google.com/appengine/docs/python/taskqueue/rest/tasks
:rtype: :class:`datetime.datetime` or ``NoneType``
:returns: Datetime object parsed from microsecond timestamp, or
``None`` if the property is not set locally.
"""
value = self._properties.get('enqueueTimestamp')
if value is not None:
return _datetime_from_microseconds(int(value))
|
https://github.com/basvandenbroek/gcloud_taskqueue/blob/b147b57f7c0ad9e8030ee9797d6526a448aa5007/gcloud_taskqueue/task.py#L177-L188
|
finding time elapsed using a timer
|
python
|
def increment_time_by(self, secs):
"""This is called when wpilib.Timer.delay() occurs"""
self.slept = [True] * 3
was_paused = False
with self.lock:
self._increment_tm(secs)
while self.paused and secs > 0:
if self.pause_secs is not None:
# if pause_secs is set, this means it was a step operation,
# so we adjust the wait accordingly
if secs > self.pause_secs:
secs -= self.pause_secs
else:
secs = 0
self.pause_secs = None
was_paused = True
self.lock.wait()
# if the operator tried to do another step, this will update
# the paused flag so we don't escape the loop
self._increment_tm(secs)
if not was_paused:
time.sleep(secs)
|
https://github.com/robotpy/pyfrc/blob/7672ea3f17c8d4b702a9f18a7372d95feee7e37d/lib/pyfrc/sim/sim_time.py#L62-L93
|
finding time elapsed using a timer
|
python
|
def tick(self):
"""
Emulate a timer: in order to avoid a real timer we "tick" a number
of times depending on the actual time passed since the last tick
"""
now = time.time()
elapsed = now - self.latest_tick
if elapsed > self.tick_interval:
ticks = int(elapsed / self.tick_interval)
self.tick_all(ticks)
self.latest_tick = now
|
https://github.com/avalente/appmetrics/blob/366fc7e1ca897e49a2227cbfa43bfa02a47f1acc/appmetrics/meter.py#L136-L151
|
finding time elapsed using a timer
|
python
|
def get_timestamp_at(time_in=None, time_at=None):
'''
Computes the timestamp for a future event that may occur in ``time_in`` time
or at ``time_at``.
'''
if time_in:
if isinstance(time_in, int):
hours = 0
minutes = time_in
else:
time_in = time_in.replace('h', ':')
time_in = time_in.replace('m', '')
try:
hours, minutes = time_in.split(':')
except ValueError:
hours = 0
minutes = time_in
if not minutes:
minutes = 0
hours, minutes = int(hours), int(minutes)
dt = timedelta(hours=hours, minutes=minutes)
time_now = datetime.utcnow()
time_at = time_now + dt
return time.mktime(time_at.timetuple())
elif time_at:
log.debug('Predicted at specified as %s', time_at)
if isinstance(time_at, (six.integer_types, float)):
# then it's a timestamp
return time_at
else:
fmts = ('%H%M', '%Hh%M', '%I%p', '%I:%M%p', '%I:%M %p')
# Support different formats for the timestamp
# The current formats accepted are the following:
#
# - 18:30 (and 18h30)
# - 1pm (no minutes, fixed hour)
# - 1:20am (and 1:20am - with or without space)
for fmt in fmts:
try:
log.debug('Trying to match %s', fmt)
dt = datetime.strptime(time_at, fmt)
return time.mktime(dt.timetuple())
except ValueError:
log.debug('Did not match %s, continue searching', fmt)
continue
msg = '{pat} does not match any of the accepted formats: {fmts}'.format(pat=time_at,
fmts=', '.join(fmts))
log.error(msg)
raise ValueError(msg)
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/timeutil.py#L18-L66
|
finding time elapsed using a timer
|
python
|
def getTime(self):
"""Get the RTC time. Returns a datetime object, or NULL if the clock is not set"""
command = '$GT'
time = self.sendCommand(command)
if time == ['OK','165', '165', '165', '165', '165', '85']:
return NULL
else:
return datetime.datetime(year = int(time[1])+2000,
month = int(time[2]),
day = int(time[3]),
hour = int(time[4]),
minute = int(time[5]),
second = int(time[6]))
|
https://github.com/miniconfig/python-openevse-wifi/blob/42fabeae052a9f82092fa9220201413732e38bb4/openevsewifi/__init__.py#L258-L270
|
finding time elapsed using a timer
|
python
|
def elapsed_time_from(start_time):
"""calculate time delta from latched time and current time"""
time_then = make_time(start_time)
time_now = datetime.utcnow().replace(microsecond=0)
if time_then is None:
return
delta_t = time_now - time_then
return delta_t
|
https://github.com/wadda/gps3/blob/91adcd7073b891b135b2a46d039ce2125cf09a09/examples/human.py#L89-L96
|
finding time elapsed using a timer
|
python
|
def humanTimeConverter():
'''
Cope whether we're passed a time in seconds on the command line or via stdin
'''
if len(sys.argv) == 2:
print humanFriendlyTime(seconds=int(sys.argv[1]))
else:
for line in sys.stdin:
print humanFriendlyTime(int(line))
sys.exit(0)
|
https://github.com/unixorn/logrus/blob/d1af28639fd42968acc257476d526d9bbe57719f/logrus/time.py#L32-L41
|
finding time elapsed using a timer
|
python
|
def print_timer(self, timer_name, **kwargs):
''' prints the timer to the terminal
keyword args:
delete -> True/False -deletes the timer after printing
'''
if hasattr(self, timer_name):
_delete_timer = kwargs.get("delete", False)
print("|-------- {} [Time Log Calculation]-----------------|".format(\
timer_name))
print("StartDiff\tLastNodeDiff\tNodeName")
time_log = getattr(self, timer_name)
start_time = time_log[0]['time']
previous_time = start_time
for entry in time_log:
time_diff = (entry['time'] - previous_time) *1000
time_from_start = (entry['time'] - start_time) * 1000
previous_time = entry['time']
print("{:.1f}\t\t{:.1f}\t\t{}".format(time_from_start,
time_diff,
entry['node']))
print("|--------------------------------------------------------|")
if _delete_timer:
self.delete_timer(timer_name)
|
https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/utilities/codetimer.py#L25-L48
|
finding time elapsed using a timer
|
python
|
def timestr_to_seconds(
x: Union[dt.date, str], *, inverse: bool = False, mod24: bool = False
) -> int:
"""
Given an HH:MM:SS time string ``x``, return the number of seconds
past midnight that it represents.
In keeping with GTFS standards, the hours entry may be greater than
23.
If ``mod24``, then return the number of seconds modulo ``24*3600``.
If ``inverse``, then do the inverse operation.
In this case, if ``mod24`` also, then first take the number of
seconds modulo ``24*3600``.
"""
if not inverse:
try:
hours, mins, seconds = x.split(":")
result = int(hours) * 3600 + int(mins) * 60 + int(seconds)
if mod24:
result %= 24 * 3600
except:
result = np.nan
else:
try:
seconds = int(x)
if mod24:
seconds %= 24 * 3600
hours, remainder = divmod(seconds, 3600)
mins, secs = divmod(remainder, 60)
result = f"{hours:02d}:{mins:02d}:{secs:02d}"
except:
result = np.nan
return result
|
https://github.com/mrcagney/gtfstk/blob/c91494e6fefc02523889655a0dc92d1c0eee8d03/gtfstk/helpers.py#L39-L70
|
finding time elapsed using a timer
|
python
|
def _GetTimeValues(self, number_of_seconds):
"""Determines time values.
Args:
number_of_seconds (int|decimal.Decimal): number of seconds.
Returns:
tuple[int, int, int, int]: days, hours, minutes, seconds.
"""
number_of_seconds = int(number_of_seconds)
number_of_minutes, seconds = divmod(number_of_seconds, 60)
number_of_hours, minutes = divmod(number_of_minutes, 60)
number_of_days, hours = divmod(number_of_hours, 24)
return number_of_days, hours, minutes, seconds
|
https://github.com/log2timeline/dfdatetime/blob/141ca4ef1eff3d354b5deaac3d81cb08506f98d6/dfdatetime/interface.py#L790-L803
|
finding time elapsed using a timer
|
python
|
def ctime(self):
"""
Get most recent create time in timestamp.
"""
try:
return self._stat.st_ctime
except: # pragma: no cover
self._stat = self.stat()
return self.ctime
|
https://github.com/MacHu-GWU/pathlib_mate-project/blob/f9fb99dd7cc9ea05d1bec8b9ce8f659e8d97b0f1/pathlib_mate/mate_attr_accessor.py#L150-L158
|
finding time elapsed using a timer
|
python
|
def __decode_time(self, t):
"""
Decode a timestamp retrieved from the timeclock
copied from zkemsdk.c - DecodeTime
"""
t = unpack("<I", t)[0]
second = t % 60
t = t // 60
minute = t % 60
t = t // 60
hour = t % 24
t = t // 24
day = t % 31 + 1
t = t // 31
month = t % 12 + 1
t = t // 12
year = t + 2000
d = datetime(year, month, day, hour, minute, second)
return d
|
https://github.com/fananimi/pyzk/blob/1a765d616526efdcb4c9adfcc9b1d10f6ed8b938/zk/base.py#L309-L336
|
finding time elapsed using a timer
|
python
|
def is_time(self):
"""Determine if a data record is of type TIME."""
dt = DATA_TYPES['time']
if type(self.data) is dt['type'] and ':' in str(self.data) and str(self.data).count(':') == 2:
# Separate hour, month, second
date_split = str(self.data).split(':')
h, m, s = date_split[0], date_split[1], date_split[2]
# Validate values
valid_hour, valid_min, valid_sec = int(h) in HOURS, int(m) in MINUTES, int(float(s)) in SECONDS
if all(i is True for i in (valid_hour, valid_min, valid_sec)):
self.type = 'time'.upper()
self.len = None
return True
|
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/datatypes/dates.py#L40-L54
|
finding time elapsed using a timer
|
python
|
def get_time_interval(time1, time2):
'''get the interval of two times'''
try:
#convert time to timestamp
time1 = time.mktime(time.strptime(time1, '%Y/%m/%d %H:%M:%S'))
time2 = time.mktime(time.strptime(time2, '%Y/%m/%d %H:%M:%S'))
seconds = (datetime.datetime.fromtimestamp(time2) - datetime.datetime.fromtimestamp(time1)).seconds
#convert seconds to day:hour:minute:second
days = seconds / 86400
seconds %= 86400
hours = seconds / 3600
seconds %= 3600
minutes = seconds / 60
seconds %= 60
return '%dd %dh %dm %ds' % (days, hours, minutes, seconds)
except:
return 'N/A'
|
https://github.com/Microsoft/nni/blob/c7cc8db32da8d2ec77a382a55089f4e17247ce41/tools/nni_cmd/nnictl_utils.py#L389-L405
|
finding time elapsed using a timer
|
python
|
def time(self):
"""Retrieve the current time from the redis server.
:rtype: float
:raises: :exc:`~tredis.exceptions.RedisError`
"""
def format_response(value):
"""Format a TIME response into a datetime.datetime
:param list value: TIME response is a list of the number
of seconds since the epoch and the number of micros
as two byte strings
:rtype: float
"""
seconds, micros = value
return float(seconds) + (float(micros) / 1000000.0)
return self._execute([b'TIME'], format_callback=format_response)
|
https://github.com/gmr/tredis/blob/2e91c6a58a35460be0525c51ac6a98fde3b506ad/tredis/server.py#L147-L167
|
finding time elapsed using a timer
|
python
|
def get_time():
"""Get time from a locally running NTP server"""
time_request = '\x1b' + 47 * '\0'
now = struct.unpack("!12I", ntp_service.request(time_request, timeout=5.0).data.read())[10]
return time.ctime(now - EPOCH_START)
|
https://github.com/hugapi/hug/blob/080901c81576657f82e2432fd4a82f1d0d2f370c/examples/use_socket.py#L14-L19
|
finding time elapsed using a timer
|
python
|
def gettime_s(text):
"""
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.
"""
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
|
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/profiler/widgets/profilergui.py#L378-L403
|
finding time elapsed using a timer
|
python
|
def _determine_timeinterval(self):
"""Return a dictionary with two datetime objects, start_time and end_time,
covering the interval of the training job
"""
description = self._sage_client.describe_training_job(TrainingJobName=self.name)
start_time = self._start_time or description[u'TrainingStartTime'] # datetime object
# Incrementing end time by 1 min since CloudWatch drops seconds before finding the logs.
# This results in logs being searched in the time range in which the correct log line was not present.
# Example - Log time - 2018-10-22 08:25:55
# Here calculated end time would also be 2018-10-22 08:25:55 (without 1 min addition)
# CW will consider end time as 2018-10-22 08:25 and will not be able to search the correct log.
end_time = self._end_time or description.get(
u'TrainingEndTime', datetime.datetime.utcnow()) + datetime.timedelta(minutes=1)
return {
'start_time': start_time,
'end_time': end_time,
}
|
https://github.com/aws/sagemaker-python-sdk/blob/a9e724c7d3f5572b68c3903548c792a59d99799a/src/sagemaker/analytics.py#L249-L266
|
finding time elapsed using a timer
|
python
|
def extractTimes(self, inp):
"""Extracts time-related information from an input string.
Ignores any information related to the specific date, focusing
on the time-of-day.
Args:
inp (str): Input string to be parsed.
Returns:
A list of datetime objects containing the extracted times from the
input snippet, or an empty list if none found.
"""
def handleMatch(time):
relative = False
if not time:
return None
# Default times: 8am, 12pm, 7pm
elif time.group(1) == 'morning':
h = 8
m = 0
elif time.group(1) == 'afternoon':
h = 12
m = 0
elif time.group(1) == 'evening':
h = 19
m = 0
elif time.group(4) and time.group(5):
h, m = 0, 0
# Extract hours difference
converter = NumberService()
try:
diff = converter.parse(time.group(4))
except:
return None
if time.group(5) == 'hours':
h += diff
else:
m += diff
# Extract minutes difference
if time.group(6):
converter = NumberService()
try:
diff = converter.parse(time.group(7))
except:
return None
if time.group(8) == 'hours':
h += diff
else:
m += diff
relative = True
else:
# Convert from "HH:MM pm" format
t = time.group(2)
h, m = int(t.split(':')[0]) % 12, int(t.split(':')[1])
try:
if time.group(3) == 'pm':
h += 12
except IndexError:
pass
if relative:
return self.now + datetime.timedelta(hours=h, minutes=m)
else:
return datetime.datetime(
self.now.year, self.now.month, self.now.day, h, m
)
inp = self._preprocess(inp)
return [handleMatch(time) for time in self._timeRegex.finditer(inp)]
|
https://github.com/crm416/semantic/blob/46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe/semantic/dates.py#L263-L339
|
finding time elapsed using a timer
|
python
|
def extract_time(match):
"""extract time from a time_re match."""
hour = int(match.group('hour'))
minute = int(match.group('minute'))
return dt.time(hour, minute)
|
https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/__init__.py#L40-L44
|
finding time elapsed using a timer
|
python
|
def get_time():
"""
Gets current time in a form of a formated string. Used in logger function.
"""
import datetime
time=make_pathable_string('%s' % datetime.datetime.now())
return time.replace('-','_').replace(':','_').replace('.','_')
|
https://github.com/rraadd88/rohan/blob/b0643a3582a2fffc0165ace69fb80880d92bfb10/rohan/dandage/io_strs.py#L174-L181
|
finding time elapsed using a timer
|
python
|
def clock(seg, seconds):
"""
Display current time on device.
"""
interval = 0.5
for i in range(int(seconds / interval)):
now = datetime.now()
seg.text = now.strftime("%H-%M-%S")
# calculate blinking dot
if i % 2 == 0:
seg.text = now.strftime("%H-%M-%S")
else:
seg.text = now.strftime("%H %M %S")
time.sleep(interval)
|
https://github.com/rm-hull/luma.led_matrix/blob/62e90aa0c052c869856a936bd76d6d86baf4ad8e/examples/sevensegment_demo.py#L26-L41
|
finding time elapsed using a timer
|
python
|
def check(self):
"""
Returns #True if the time interval has passed.
"""
if self.value is None:
return True
return (time.clock() - self.start) >= self.value
|
https://github.com/NiklasRosenstein/myo-python/blob/89a7480f8058061da7a3dd98ccec57a6b134ddf3/myo/utils.py#L37-L44
|
finding time elapsed using a timer
|
python
|
def ttl(self, steps, relative_time=None):
'''
Return the ttl given the number of steps, None if steps is not defined
or we're otherwise unable to calculate one. If relative_time is defined,
then return a ttl that is the number of seconds from now that the
record should be expired.
'''
if steps:
# Approximate the ttl based on number of seconds, since it's
# "close enough"
if relative_time:
rtime = self.to_bucket(relative_time)
ntime = self.to_bucket(time.time())
# Convert to number of days
day_diff = (self.from_bucket(ntime, native=True) - self.from_bucket(rtime, native=True)).days
# Convert steps to number of days as well
step_diff = (steps*SIMPLE_TIMES[self._step[0]]) / SIMPLE_TIMES['d']
# The relative time is beyond our TTL cutoff
if day_diff > step_diff:
return 0
# The relative time is in "recent" past or future
else:
return (step_diff - day_diff) * SIMPLE_TIMES['d']
return steps * SIMPLE_TIMES[ self._step[0] ]
return None
|
https://github.com/agoragames/kairos/blob/0b062d543b0f4a46df460fa0eb6ec281232ab179/kairos/timeseries.py#L237-L264
|
finding time elapsed using a timer
|
python
|
def FunctionTimer(on_done=None):
'''
To check execution time of a function
borrowed from https://medium.com/pythonhive/python-decorator-to-measure-the-execution-time-of-methods-fa04cb6bb36d
>>> def logger(details, args, kwargs): #some function that uses the time output
... print(details)
...
>>> @FunctionTimer(on_done= logger)
... def foo(t=10):
... print('foo executing...')
... time.sleep(t)
...
>>> @FunctionTimer(on_done= logger)
... def bar(t, n):
... for i in range(n):
... print('bar executing...')
... time.sleep(1)
... foo(t)
...
>>> bar(3,2)
bar executing...
bar executing...
foo executing...
('foo', 3)
('bar', 5)
'''
def decfn(fn):
def timed(*args, **kwargs):
ts = time.time()
result = fn(*args, **kwargs)
te = time.time()
if on_done:
on_done((fn.__name__,int(te - ts)), args, kwargs)
else:
print(('%r %d sec(s)' % (fn.__name__, (te - ts))))
return result
return timed
return decfn
|
https://github.com/deep-compute/deeputil/blob/9af5702bc3fd990688bf2aed16c20fa104be66df/deeputil/timer.py#L5-L47
|
finding time elapsed using a timer
|
python
|
def getTimeSinceLastVsync(self):
"""
Returns the number of elapsed seconds since the last recorded vsync event. This
will come from a vsync timer event in the timer if possible or from the application-reported
time if that is not available. If no vsync times are available the function will
return zero for vsync time and frame counter and return false from the method.
"""
fn = self.function_table.getTimeSinceLastVsync
pfSecondsSinceLastVsync = c_float()
pulFrameCounter = c_uint64()
result = fn(byref(pfSecondsSinceLastVsync), byref(pulFrameCounter))
return result, pfSecondsSinceLastVsync.value, pulFrameCounter.value
|
https://github.com/cmbruns/pyopenvr/blob/68395d26bb3df6ab1f0f059c38d441f962938be6/src/openvr/__init__.py#L2681-L2693
|
finding time elapsed using a timer
|
python
|
def next_timer_delta(self):
"Returns a timevalue that the proactor will wait on."
if self.timeouts and not self.active:
now = getnow()
timo = self.timeouts[0].timeout
if now >= timo:
#looks like we've exceded the time
return 0
else:
return (timo - now)
else:
if self.active:
return 0
else:
return None
|
https://github.com/ionelmc/python-cogen/blob/83b0edb88425eba6e5bfda9f1dcd34642517e2a8/cogen/core/schedulers.py#L100-L114
|
finding time elapsed using a timer
|
python
|
def mark_time(times, msg=None):
"""
Time measurement utility.
Measures times of execution between subsequent calls using
time.clock(). The time is printed if the msg argument is not None.
Examples
--------
>>> times = []
>>> mark_time(times)
... do something
>>> mark_time(times, 'elapsed')
elapsed 0.1
... do something else
>>> mark_time(times, 'elapsed again')
elapsed again 0.05
>>> times
[0.10000000000000001, 0.050000000000000003]
"""
tt = time.clock()
times.append(tt)
if (msg is not None) and (len(times) > 1):
print msg, times[-1] - times[-2]
|
https://github.com/vlukes/dicom2fem/blob/3056c977ca7119e01984d3aa0c4448a1c6c2430f/dicom2fem/base.py#L99-L123
|
finding time elapsed using a timer
|
python
|
def getmtime(self, path=None, client_kwargs=None, header=None):
"""
Return the time of last access of path.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
float: The number of seconds since the epoch
(see the time module).
"""
return self._getmtime_from_header(
self.head(path, client_kwargs, header))
|
https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_system.py#L199-L213
|
finding time elapsed using a timer
|
python
|
def get_time_inqueue(self):
"""
:class:`timedelta` with the time spent in the Queue, None if the Task is not running
.. note:
This value is always greater than the real value computed by the resource manager
as we start to count only when check_status sets the `Task` status to S_RUN.
"""
if self.submission is None: return None
if self.start is None:
delta = datetime.datetime.now() - self.submission
else:
delta = self.start - self.submission
# This happens when we read the exact start datetime from the ABINIT log file.
if delta.total_seconds() < 0: delta = datetime.timedelta(seconds=0)
return MyTimedelta.as_timedelta(delta)
|
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/abinit/tasks.py#L1278-L1296
|
finding time elapsed using a timer
|
python
|
def countdown(
seconds=None,
block=True,
interval=1,
daemon=True,
tick_callback=None,
finish_callback=None,
):
"""Run a countdown function to wait something, similar to threading.Timer,
but will show the detail tick by tick_callback.
::
from torequests.utils import countdown
countdown(3)
# 3 2 1
# countdown finished [3 seconds]: 2018-06-13 00:12:55 => 2018-06-13 00:12:58.
countdown('2018-06-13 00:13:29')
# 10 9 8 7 6 5 4 3 2 1
# countdown finished [10 seconds]: 2018-06-13 00:13:18 => 2018-06-13 00:13:28.
"""
def default_tick_callback(s, seconds, *args):
flush_print(s, sep="", end=" ")
def default_finish_callback(seconds, start_time):
flush_print()
def cd(seconds, interval):
for s in range(seconds, 0, -interval):
tick_callback(s, seconds, interval)
time.sleep(interval)
if callable(finish_callback):
finish_callback(seconds, start_time)
start_time = time.time()
tick_callback = tick_callback or default_tick_callback
finish_callback = (
default_finish_callback if finish_callback is None else finish_callback
)
if unicode(seconds).isdigit():
seconds = int(seconds)
elif isinstance(seconds, (unicode, str)):
seconds = int(ptime(seconds) - time.time())
t = Thread(target=cd, args=(seconds, interval))
t.daemon = daemon
t.start()
if block:
t.join()
|
https://github.com/ClericPy/torequests/blob/1793261688d7a47e1c3a0830d83f8552f5e3e5d9/torequests/utils.py#L1304-L1353
|
finding time elapsed using a timer
|
python
|
def set_timer(self, timer="wall"):
"""Set the timer function
Parameters
----------
timer : {'wall', 'cpu', or callable}
Timer function used to measure task running times.
'wall' uses `time.time`, 'cpu' uses `time.process_time`
Returns
-------
self
"""
if timer == "wall":
timer = time.time
elif timer == "cpu":
try:
timer = time.process_time
except AttributeError:
raise RuntimeError(
"Python2.7 on Windows does not offer a CPU time function. "
"Please upgrade to Python >= 3.5.")
self.timer = timer
return self
|
https://github.com/scottgigante/tasklogger/blob/06a263715d2db0653615c17b2df14b8272967b8d/tasklogger/logger.py#L98-L121
|
finding time elapsed using a timer
|
python
|
def time(self, intervals=1, *args, _show_progress=True, _print=True,
_collect_garbage=False, **kwargs):
""" Measures the execution time of :prop:_callables for @intervals
@intervals: #int number of intervals to measure the execution time
of the function for
@*args: arguments to pass to the callable being timed
@**kwargs: arguments to pass to the callable being timed
@_show_progress: #bool whether or not to print a progress bar
@_print: #bool whether or not to print the results of the timing
@_collect_garbage: #bool whether or not to garbage collect
while timing
@_quiet: #bool whether or not to disable the print() function's
ability to output to terminal during the timing
-> #tuple of :class:Timer :prop:results of timing
"""
self.reset()
self.num_intervals = intervals
for func in self.progress(self._callables):
try:
#: Don't ruin all timings if just one doesn't work
t = Timer(
func, _precision=self.precision,
_parent_progressbar=self.progress)
t.time(
intervals, *args, _print=False,
_show_progress=_show_progress,
_collect_garbage=_collect_garbage,
**kwargs)
except Exception as e:
print(RuntimeWarning(
"{} with {}".format(colorize(
"{} failed".format(Look.pretty_objname(
func, color="yellow")), "yellow"), repr(e))))
self._callable_results.append(t)
self.progress.update()
self.info(_print=_print)
return self.results
|
https://github.com/jaredLunde/redis_structures/blob/b9cce5f5c85db5e12c292633ff8d04e3ae053294/redis_structures/debug/__init__.py#L2249-L2287
|
finding time elapsed using a timer
|
python
|
def get_recent_mtime(t):
'''获取更精简的时间.
如果是当天的, 就返回时间; 如果是当年的, 就近回月份和日期; 否则返回完整的时间
'''
if isinstance(t, int):
# ignore micro seconds
if len(str(t)) == 13:
t = t // 1000
t = datetime.datetime.fromtimestamp(t)
now = datetime.datetime.now()
delta = now - t
if delta.days == 0:
return datetime.datetime.strftime(t, '%H:%M:%S')
elif now.year == t.year:
return datetime.datetime.strftime(t, '%b %d')
else:
return datetime.datetime.strftime(t, '%b %d %Y')
|
https://github.com/XuShaohua/bcloud/blob/4b54e0fdccf2b3013285fef05c97354cfa31697b/bcloud/util.py#L79-L96
|
finding time elapsed using a timer
|
python
|
def current_time(self) -> datetime:
"""Extract current time."""
_date = datetime.strptime(self.obj.SBRes.SBReq.StartT.get("date"), "%Y%m%d")
_time = datetime.strptime(self.obj.SBRes.SBReq.StartT.get("time"), "%H:%M")
return datetime.combine(_date.date(), _time.time())
|
https://github.com/cgtobi/PyRMVtransport/blob/20a0d68ecfdedceb32e8ca96c381fdec7e2069c7/RMVtransport/rmvtransport.py#L146-L150
|
finding time elapsed using a timer
|
python
|
def now(self, when=None):
"""Set the current value to the correct tuple based on the seconds
since the epoch. If 'when' is not provided, get the current time
from the task manager.
"""
if when is None:
when = _TaskManager().get_time()
tup = time.localtime(when)
self.value = (tup[0]-1900, tup[1], tup[2], tup[6] + 1)
return self
|
https://github.com/JoelBender/bacpypes/blob/4111b8604a16fa2b7f80d8104a43b9f3e28dfc78/py34/bacpypes/primitivedata.py#L1407-L1418
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.