本文整理汇总了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)
示例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()
示例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
示例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)})
示例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']
示例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
示例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()
示例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
示例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')
示例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)
示例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())
示例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())
示例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.')
示例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
示例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)