當前位置: 首頁>>代碼示例>>Python>>正文


Python datetime.timedelta方法代碼示例

本文整理匯總了Python中datetime.timedelta方法的典型用法代碼示例。如果您正苦於以下問題:Python datetime.timedelta方法的具體用法?Python datetime.timedelta怎麽用?Python datetime.timedelta使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在datetime的用法示例。


在下文中一共展示了datetime.timedelta方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: run

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import timedelta [as 別名]
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) 
開發者ID:svviz,項目名稱:svviz,代碼行數:26,代碼來源:runTests.py

示例2: get_kms_auth_token

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import timedelta [as 別名]
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() 
開發者ID:kislyuk,項目名稱:aegea,代碼行數:18,代碼來源:ssh.py

示例3: describe_bucket_worker

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import timedelta [as 別名]
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 
開發者ID:kislyuk,項目名稱:aegea,代碼行數:19,代碼來源:s3.py

示例4: cluster_memory_reservation

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import timedelta [as 別名]
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)}) 
開發者ID:omerxx,項目名稱:ecscale,代碼行數:23,代碼來源:ecscale.py

示例5: ec2_avg_cpu_utilization

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import timedelta [as 別名]
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'] 
開發者ID:omerxx,項目名稱:ecscale,代碼行數:19,代碼來源:ecscale.py

示例6: natural_time

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import timedelta [as 別名]
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 
開發者ID:pkkid,項目名稱:pkmeter,代碼行數:21,代碼來源:utils.py

示例7: update

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import timedelta [as 別名]
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() 
開發者ID:pkkid,項目名稱:pkmeter,代碼行數:23,代碼來源:gcal.py

示例8: _parse_events

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import timedelta [as 別名]
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 
開發者ID:pkkid,項目名稱:pkmeter,代碼行數:19,代碼來源:gcal.py

示例9: save

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import timedelta [as 別名]
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') 
開發者ID:cherrypy,項目名稱:cherrypy,代碼行數:26,代碼來源:sessions.py

示例10: time_since_initialized

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import timedelta [as 別名]
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) 
開發者ID:mbusb,項目名稱:multibootusb,代碼行數:19,代碼來源:_device.py

示例11: test_should_refresh

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import timedelta [as 別名]
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()) 
開發者ID:alexcasalboni,項目名稱:ssm-cache-python,代碼行數:21,代碼來源:cache_test.py

示例12: test_main_with_expiration_group

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import timedelta [as 別名]
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()) 
開發者ID:alexcasalboni,項目名稱:ssm-cache-python,代碼行數:22,代碼來源:cache_test.py

示例13: CertificateExpired

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import timedelta [as 別名]
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.') 
開發者ID:google,項目名稱:macops,代碼行數:21,代碼來源:certs.py

示例14: __init__

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import timedelta [as 別名]
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 
開發者ID:supakeen,項目名稱:pinnwand,代碼行數:24,代碼來源:database.py

示例15: add

# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import timedelta [as 別名]
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) 
開發者ID:supakeen,項目名稱:pinnwand,代碼行數:20,代碼來源:command.py


注:本文中的datetime.timedelta方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。