Python datetime.timedelta() Examples
The following are 30
code examples of datetime.timedelta().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
datetime
, or try the search function
.
Example #1
Source File: runTests.py From svviz with MIT License | 7 votes |
def run(which): print("running all tests...") summary = pandas.DataFrame(columns=["pass", "info", "timing"]) # Test chromosome ends if len(which)==0 or "chrom_ends" in which: summary.loc["chrom_ends"] = _runTest(runTestIssues, "issues") # Run the demos if len(which)==0 or "demos" in which: summary.loc["demos"] = _runTest(testDemos.run, "demos") # Run regression testing on ref/alt/amb counts if len(which)==0 or "counts" in which: summary.loc["counts"] = _runTest(runTestCounts, "counts") # Run the render regression tests if len(which)==0 or "rendering" in which: summary.loc["rendering"] = _runTest(rendertest.run, "rendering") summary["timing"] = summary["timing"].apply(lambda x: "{}".format(datetime.timedelta(seconds=int(x)))) print(summary) saveTimingInfo(summary)
Example #2
Source File: run.py From mutatest with MIT License | 7 votes |
def clean_trial(src_loc: Path, test_cmds: List[str]) -> timedelta: """Remove all existing cache files and run the test suite. Args: src_loc: the directory of the package for cache removal, may be a file test_cmds: test running commands for subprocess.run() Returns: None Raises: BaselineTestException: if the clean trial does not pass from the test run. """ cache.remove_existing_cache_files(src_loc) LOGGER.info("Running clean trial") # clean trial will show output all the time for diagnostic purposes start = datetime.now() clean_run = subprocess.run(test_cmds, capture_output=False) end = datetime.now() if clean_run.returncode != 0: raise BaselineTestException( f"Clean trial does not pass, mutant tests will be meaningless.\n" f"Output: {str(clean_run.stdout)}" ) return end - start #################################################################################################### # MUTATION SAMPLE GENERATION ####################################################################################################
Example #3
Source File: _device.py From multibootusb with GNU General Public License v2.0 | 6 votes |
def time_since_initialized(self): """ The time elapsed since initialization as :class:`~datetime.timedelta`. This property is only implemented on devices, which need to store properties in the udev database. On all other devices this property is simply zero :class:`~datetime.timedelta`. .. seealso:: :attr:`is_initialized` .. udevversion:: 165 .. versionadded:: 0.8 """ microseconds = self._libudev.udev_device_get_usec_since_initialized( self) return timedelta(microseconds=microseconds)
Example #4
Source File: ecscale.py From ecscale with MIT License | 6 votes |
def cluster_memory_reservation(cwClient, clusterName): # Return cluster mem reservation average per minute cloudwatch metric try: response = cwClient.get_metric_statistics( Namespace='AWS/ECS', MetricName='MemoryReservation', Dimensions=[ { 'Name': 'ClusterName', 'Value': clusterName }, ], StartTime=datetime.datetime.utcnow() - datetime.timedelta(seconds=120), EndTime=datetime.datetime.utcnow(), Period=60, Statistics=['Average'] ) return response['Datapoints'][0]['Average'] except Exception: logger({'ClusterMemoryError': 'Could not retrieve mem reservation for {}'.format(clusterName)})
Example #5
Source File: ecscale.py From ecscale with MIT License | 6 votes |
def ec2_avg_cpu_utilization(clusterName, asgData, cwclient): asg = find_asg(clusterName, asgData) response = cwclient.get_metric_statistics( Namespace='AWS/EC2', MetricName='CPUUtilization', Dimensions=[ { 'Name': 'AutoScalingGroupName', 'Value': asg }, ], StartTime=datetime.datetime.utcnow() - datetime.timedelta(seconds=120), EndTime=datetime.datetime.utcnow(), Period=60, Statistics=['Average'] ) return response['Datapoints'][0]['Average']
Example #6
Source File: utils.py From pkmeter with BSD 3-Clause "New" or "Revised" License | 6 votes |
def natural_time(timedelta, precision=2, default='NA'): # Convert timedelta to seconds remaining = timedelta if isinstance(timedelta, datetime.timedelta): remaining = (timedelta.days * 86400) + timedelta.seconds # Create and return the natural string rtnvals = [] for name, seconds in SECONDS: if remaining > seconds * 2: value = int(float(remaining) / float(seconds)) remaining = remaining - (value * seconds) rtnvals.append('%s %s' % (value, name)) precision -= 1 if precision <= 0 or remaining <= 0: break if not rtnvals: rtnvals.append('0 %s' % SECONDS[-1][0]) rtnval = ', '.join(rtnvals) return rtnval
Example #7
Source File: gcal.py From pkmeter with BSD 3-Clause "New" or "Revised" License | 6 votes |
def update(self): self.data['events'] = [] self.tzutc = tz.tzutc() self.tzlocal = tz.tzlocal() urls, colors = [], {} for cal in self._iter_calendars(): urls.append(cal.url) colors[cal.url] = cal.color for result in utils.iter_responses(urls, timeout=5): response = result.get('response') if response: ical = Calendar.from_ical(response.read().decode('utf-8')) color = colors[result.get('url')] self.data['events'] += self._parse_events(ical, color) self.data['events'] = sorted(self.data['events'], key=lambda e:e['start']) # Calculate time to next event now = datetime.datetime.now() next = [e for e in self.data['events'] if e['start'] > now][0]['start'] if self.data['events'] else self.DELTANONE if next < now + datetime.timedelta(seconds=self.DEFAULT_INTERVAL*1.5): self.data['next'] = 'Now' else: self.data['next'] = utils.natural_time(next-now, 1) super(Plugin, self).update()
Example #8
Source File: s3.py From aegea with Apache License 2.0 | 6 votes |
def describe_bucket_worker(bucket): bucket.LocationConstraint = clients.s3.get_bucket_location(Bucket=bucket.name)["LocationConstraint"] cloudwatch = resources.cloudwatch bucket_region = bucket.LocationConstraint or "us-east-1" if bucket_region != cloudwatch.meta.client.meta.region_name: cloudwatch = boto3.Session(region_name=bucket_region).resource("cloudwatch") data = get_cloudwatch_metric_stats("AWS/S3", "NumberOfObjects", start_time=datetime.utcnow() - timedelta(days=2), end_time=datetime.utcnow(), period=3600, BucketName=bucket.name, StorageType="AllStorageTypes", resource=cloudwatch) bucket.NumberOfObjects = int(data["Datapoints"][-1]["Average"]) if data["Datapoints"] else None data = get_cloudwatch_metric_stats("AWS/S3", "BucketSizeBytes", start_time=datetime.utcnow() - timedelta(days=2), end_time=datetime.utcnow(), period=3600, BucketName=bucket.name, StorageType="StandardStorage", resource=cloudwatch) bucket.BucketSizeBytes = format_number(data["Datapoints"][-1]["Average"]) if data["Datapoints"] else None return bucket
Example #9
Source File: ssh.py From aegea with Apache License 2.0 | 6 votes |
def get_kms_auth_token(session, bless_config, lambda_regional_config): logger.info("Requesting new KMS auth token in %s", lambda_regional_config["aws_region"]) token_not_before = datetime.datetime.utcnow() - datetime.timedelta(minutes=1) token_not_after = token_not_before + datetime.timedelta(hours=1) token = dict(not_before=token_not_before.strftime("%Y%m%dT%H%M%SZ"), not_after=token_not_after.strftime("%Y%m%dT%H%M%SZ")) encryption_context = { "from": session.resource("iam").CurrentUser().user_name, "to": bless_config["lambda_config"]["function_name"], "user_type": "user" } kms = session.client('kms', region_name=lambda_regional_config["aws_region"]) res = kms.encrypt(KeyId=lambda_regional_config["kms_auth_key_id"], Plaintext=json.dumps(token), EncryptionContext=encryption_context) return base64.b64encode(res["CiphertextBlob"]).decode()
Example #10
Source File: cache_test.py From ssm-cache-python with MIT License | 6 votes |
def test_should_refresh(self): """ Unit test _should_refresh private method """ # without max age ref = Refreshable(None) self.assertFalse(ref._should_refresh()) # with max age and no data ref = Refreshable(max_age=10) self.assertTrue(ref._should_refresh()) # manually force refresh time ref._last_refresh_time = datetime.utcnow() # with max age and last refreshed date OK self.assertFalse(ref._should_refresh()) # freeze_time will pretend 10 seconds have passed! with freeze_time(lambda: datetime.utcnow() + timedelta(seconds=10)): # with max age and last refreshed date KO self.assertTrue(ref._should_refresh())
Example #11
Source File: cache_test.py From ssm-cache-python with MIT License | 6 votes |
def test_main_with_expiration_group(self): """ Test group case with expiration """ group = SSMParameterGroup(max_age=300) param_1 = group.parameter("my_param_1") param_2 = group.parameter("my_param_2") param_3 = group.parameter("my_param_3") # individual params don't share max_age internally (for now) for param in (param_1, param_2, param_3): self.assertEqual(param._max_age, None) # force fetch group.refresh() # pretend time has passed (for the group) group._last_refresh_time = datetime.utcnow() - timedelta(seconds=301) self.assertTrue(group._should_refresh()) self.assertTrue(param_1._should_refresh()) self.assertTrue(param_2._should_refresh()) self.assertTrue(param_3._should_refresh())
Example #12
Source File: gcal.py From pkmeter with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _parse_events(self, ical, color): events = [] today = datetime.datetime.combine(datetime.date.today(), datetime.time.min) title = ical.get('x-wr-calname', ical.get('version', '')) for event in ical.walk(): if event.name == "VEVENT": start = self._event_start(event) if today <= start <= today + datetime.timedelta(days=14): events.append({ 'title': event.get('summary'), 'calendar': title, 'color': color, 'start': start, 'where': event.get('location'), 'status': event.get('description'), }) return events
Example #13
Source File: certs.py From macops with Apache License 2.0 | 6 votes |
def CertificateExpired(cert, expires=0): """Checks a given certificate for expiry. Args: cert: Certificate object expires: int, the number of seconds to check for expiry. 0 means now Returns: boolean, whether the certificate will expire in expires seconds Raises: CertError: cert is a mandatory argument CertError: cert is not a PEM encoded x509 cert """ expiry = datetime.datetime.today() + datetime.timedelta(seconds=expires) # enddate is a list of [str, (datetime|None)], we want the datetime object cert_end = cert.enddate[1] if cert_end: return expiry > cert_end else: raise CertError('Certificate has a malformed enddate.')
Example #14
Source File: sessions.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def save(self): """Save session data.""" try: # If session data has never been loaded then it's never been # accessed: no need to save it if self.loaded: t = datetime.timedelta(seconds=self.timeout * 60) expiration_time = self.now() + t if self.debug: cherrypy.log('Saving session %r with expiry %s' % (self.id, expiration_time), 'TOOLS.SESSIONS') self._save(expiration_time) else: if self.debug: cherrypy.log( 'Skipping save of session %r (no session loaded).' % self.id, 'TOOLS.SESSIONS') finally: if self.locked: # Always release the lock if the user didn't release it self.release_lock() if self.debug: cherrypy.log('Lock released after save.', 'TOOLS.SESSIONS')
Example #15
Source File: database.py From pinnwand with MIT License | 6 votes |
def __init__( self, slug: str, expiry: datetime.timedelta = datetime.timedelta(days=7), src: str = None, ) -> None: # Generate a paste_id and a removal_id # Unless someone proves me wrong that I need to check for collisions # my famous last words will be that the odds are astronomically small self.slug = slug self.removal = utility.slug_create(auto_scale=False) self.pub_date = datetime.datetime.utcnow() self.chg_date = datetime.datetime.utcnow() self.src = src # The expires date is the pub_date with the delta of the expiry if expiry: self.exp_date = self.pub_date + expiry else: self.exp_date = None
Example #16
Source File: command.py From pinnwand with MIT License | 6 votes |
def add(lexer: str) -> None: """Add a paste to pinnwand's database from stdin.""" from pinnwand import database from pinnwand import utility if lexer not in utility.list_languages(): log.error("add: unknown lexer") return paste = database.Paste(utility.slug_create(), expiry=timedelta(days=1)) file = database.File(paste.slug, sys.stdin.read(), lexer=lexer) paste.files.append(file) with database.session() as session: session.add(paste) session.commit() log.info("add: paste created: %s", paste.slug)
Example #17
Source File: __init__.py From Random-Erasing with Apache License 2.0 | 5 votes |
def eta_td(self): return timedelta(seconds=self.eta)
Example #18
Source File: timer_test.py From macops with Apache License 2.0 | 5 votes |
def testExpired(self): self.mox.StubOutWithMock(self.tf, 'GetOrCreateTimestamp') expired = self.interval + datetime.timedelta(minutes=1) timestamp = datetime.datetime.utcnow() - expired self.tf.GetOrCreateTimestamp().AndReturn(timestamp) self.mox.ReplayAll() self.assertTrue(self.tf.IsOlderThan(self.interval)) self.mox.VerifyAll()
Example #19
Source File: motion_detection_test.py From pynvr with BSD 3-Clause "New" or "Revised" License | 5 votes |
def canDetectMotion(self): if self.__canDetectMotion: return True if self.__camConnectionDts is None: return False minDts = self.__camConnectionDts + dts.timedelta(seconds=config.INITIAL_WAIT_INTERVAL_BEFORE_MOTION_DETECTION_SECS) if minDts > self.utcNow(): return False self.__canDetectMotion = True return True
Example #20
Source File: client.py From python-lifx-sdk with MIT License | 5 votes |
def get_devices(self, max_seen=None): """ Get a list of all responding devices. :param max_seen: The number of seconds since the device was last seen, defaults to 3 times the devicepoll interval. """ if max_seen is None: max_seen = self._devicepolltime * MISSED_POLLS seen_delta = timedelta(seconds=max_seen) devices = filter(lambda x:x.seen_ago < seen_delta, self._devices.values()) # Sort by device id to ensure consistent ordering return sorted(devices, key=lambda k:k.id)
Example #21
Source File: client.py From python-lifx-sdk with MIT License | 5 votes |
def poll_devices(self): """ Poll all devices right now. """ poll_delta = timedelta(seconds=self._devicepolltime - 1) for device in filter(lambda x:x.seen_ago > poll_delta, self._devices.values()): device.send_poll_packet()
Example #22
Source File: build_windows.py From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 | 5 votes |
def windows_build(args): logging.info("Using vcvars environment:\n{}".format(args.vcvars)) path = args.output os.makedirs(path, exist_ok=True) mxnet_root = get_mxnet_root() logging.info("Found MXNet root: {}".format(mxnet_root)) with remember_cwd(): os.chdir(path) cmd = "\"{}\" && cmake -G \"NMake Makefiles JOM\" {} {}".format(args.vcvars, CMAKE_FLAGS[args.flavour], mxnet_root) logging.info("Generating project with CMake:\n{}".format(cmd)) check_call(cmd, shell=True) cmd = "\"{}\" && jom".format(args.vcvars) logging.info("Building with jom:\n{}".format(cmd)) t0 = int(time.time()) check_call(cmd, shell=True) logging.info("Build flavour: {} complete in directory: \"{}\"".format(args.flavour, os.path.abspath(path))) logging.info("Build took {}".format(datetime.timedelta(seconds=int(time.time() - t0)))) windows_package(args)
Example #23
Source File: core.py From knob with MIT License | 5 votes |
def _parse_time(self, time): """ Taken from: https://github.com/joekickass/python-btsnoop Record time is a 64-bit signed integer representing the time of packet arrival, in microseconds since midnight, January 1st, 0 AD nominal Gregorian. In order to avoid leap-day ambiguity in calculations, note that an equivalent epoch may be used of midnight, January 1st 2000 AD, which is represented in this field as 0x00E03AB44A676000. """ time_betw_0_and_2000_ad = int("0x00E03AB44A676000", 16) time_since_2000_epoch = datetime.timedelta(microseconds=time) - datetime.timedelta(microseconds=time_betw_0_and_2000_ad) return datetime.datetime(2000, 1, 1) + time_since_2000_epoch
Example #24
Source File: cache.py From ssm-cache-python with MIT License | 5 votes |
def __init__(self, max_age): self._last_refresh_time = None self._max_age = max_age self._max_age_delta = timedelta(seconds=max_age or 0)
Example #25
Source File: __init__.py From Random-Erasing with Apache License 2.0 | 5 votes |
def elapsed_td(self): return timedelta(seconds=self.elapsed)
Example #26
Source File: util.py From kw_condition with MIT License | 5 votes |
def date_by_adding_business_days(from_date, add_days): business_days_to_add = add_days current_date = from_date while business_days_to_add > 0: current_date += datetime.timedelta(days=1) weekday = current_date.weekday() if weekday >= 5: # sunday = 6 continue business_days_to_add -= 1 return current_date
Example #27
Source File: uniborg.py From friendly-telegram with GNU Affero General Public License v3.0 | 5 votes |
def time_formatter(self, ms): return str(datetime.timedelta(milliseconds=ms))
Example #28
Source File: redisession.py From video2commons with GNU General Public License v3.0 | 5 votes |
def get_redis_expiration_time(self, app, session): """Get Redis expiration time.""" if session.permanent: return app.permanent_session_lifetime return timedelta(days=1)
Example #29
Source File: test_models.py From pythonjobs.ie with GNU General Public License v2.0 | 5 votes |
def test_get_active_jobs_return_jobs_created_at_less_than_four_months(self): now = timezone.now() + timedelta(days=121) self.job.save() self.assertEqual(len(Job.get_actives(now)), 0)
Example #30
Source File: models.py From pythonjobs.ie with GNU General Public License v2.0 | 5 votes |
def get_actives(now=timezone.now()): limit = now - timedelta(days=120) return Job.objects.filter( status=1, created_at__gt=limit).order_by("-created_at").all()