本文整理汇总了Python中datetime.datetime.utcnow方法的典型用法代码示例。如果您正苦于以下问题:Python datetime.utcnow方法的具体用法?Python datetime.utcnow怎么用?Python datetime.utcnow使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类datetime.datetime
的用法示例。
在下文中一共展示了datetime.utcnow方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: maintain_leadership
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import utcnow [as 别名]
def maintain_leadership(self, leader_id):
"""The active leader reaffirms its existence.
:param leader_id: uuid.UUID ID of the leader
"""
try:
with self.db_engine.connect() as conn:
query = self.active_instance_tbl.update().where(
self.active_instance_tbl.c.identity == leader_id.
bytes).values(last_ping=datetime.utcnow())
rs = conn.execute(query)
rc = rs.rowcount
if rc == 1:
return True
else:
return False
except Exception as ex:
self.logger.error("Error maintaining leadership: %s" % str(ex))
示例2: test_build_data_insert_iwth_collected_date
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import utcnow [as 别名]
def test_build_data_insert_iwth_collected_date(self, blank_state):
"""Test that build data can be inserted specifying collection date."""
build_data_fields = {
'node_name': 'foo',
'generator': 'hello_world',
'data_format': 'text/plain',
'data_element': 'Hello World!',
'task_id': uuid.uuid4(),
'collected_date': datetime.utcnow(),
}
build_data = objects.BuildData(**build_data_fields)
result = blank_state.post_build_data(build_data)
assert result
示例3: test_build_data_select
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import utcnow [as 别名]
def test_build_data_select(self, blank_state):
"""Test that build data can be deserialized from the database."""
build_data_fields = {
'node_name': 'foo',
'generator': 'hello_world',
'data_format': 'text/plain',
'data_element': 'Hello World!',
'task_id': uuid.uuid4(),
'collected_date': datetime.utcnow(),
}
build_data = objects.BuildData(**build_data_fields)
result = blank_state.post_build_data(build_data)
assert result
bd_list = blank_state.get_build_data()
assert len(bd_list) == 1
assert bd_list[0].to_dict() == build_data.to_dict()
示例4: describe_bucket_worker
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import utcnow [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
示例5: ls
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import utcnow [as 别名]
def ls(args):
bucket = resources.s3.Bucket(args.billing_reports_bucket.format(account_id=ARN.get_account_id()))
now = datetime.utcnow()
year = args.year or now.year
month = str(args.month or now.month).zfill(2)
next_year = year + ((args.month or now.month) + 1) // 12
next_month = str(((args.month or now.month) + 1) % 12).zfill(2)
manifest_name = "aegea/{report}/{yr}{mo}01-{next_yr}{next_mo}01/{report}-Manifest.json"
manifest_name = manifest_name.format(report=__name__, yr=year, mo=month, next_yr=next_year, next_mo=next_month)
try:
manifest = json.loads(bucket.Object(manifest_name).get().get("Body").read())
for report_key in manifest["reportKeys"]:
report = BytesIO(bucket.Object(report_key).get().get("Body").read())
with gzip.GzipFile(fileobj=report) as fh:
reader = csv.DictReader(fh)
for line in reader:
page_output(tabulate(filter_line_items(reader, args), args))
except ClientError as e:
msg = 'Unable to get report {} from {}: {}. Run "aegea billing configure" to enable reports.'
raise AegeaException(msg.format(manifest_name, bucket, e))
示例6: logs
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import utcnow [as 别名]
def logs(args):
if args.log_group and (args.log_stream or args.start_time or args.end_time):
if args.export and args.print_s3_urls:
return ["s3://{}/{}".format(f.bucket_name, f.key) for f in export_log_files(args)]
elif args.export:
return export_and_print_log_events(args)
else:
return print_log_events(args)
table = []
group_cols = ["logGroupName"]
stream_cols = ["logStreamName", "lastIngestionTime", "storedBytes"]
args.columns = group_cols + stream_cols
for group in paginate(clients.logs.get_paginator("describe_log_groups")):
if args.log_group and group["logGroupName"] != args.log_group:
continue
n = 0
for stream in paginate(clients.logs.get_paginator("describe_log_streams"),
logGroupName=group["logGroupName"], orderBy="LastEventTime", descending=True):
now = datetime.utcnow().replace(microsecond=0)
stream["lastIngestionTime"] = now - datetime.utcfromtimestamp(stream.get("lastIngestionTime", 0) // 1000)
table.append(dict(group, **stream))
n += 1
if n >= args.max_streams_per_group:
break
page_output(tabulate(table, args))
示例7: slackMsg
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import utcnow [as 别名]
def slackMsg(item,color,link, size):
# line 101
if slack_token == "":
return
sc = SlackClient(slack_token)
text = item+"\n"
text += color+'\n'
text += size.title()+'\n'
text += link+'\n'
text += "Restock!"+'\n'
text += str(datetime.utcnow().strftime('%H:%M:%S.%f')[:-3])
sc.api_call(
"chat.postMessage",
channel="#test",
text=text
)
示例8: sendTweet
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import utcnow [as 别名]
def sendTweet(item,color,link, size):
# line 102
auth = tweepy.OAuthHandler(C_KEY, C_SECRET)
auth.set_access_token(A_TOKEN, A_TOKEN_SECRET)
api = tweepy.API(auth)
tweet = item+"\n"
tweet += color+'\n'
tweet += size.title()+'\n'
tweet += link+'\n'
tweet += "Restock!"+'\n'
tweet += str(datetime.utcnow().strftime('%H:%M:%S.%f')[:-3])
try:
api.update_status(tweet)
print(tweet)
except:
print("Error sending tweet!")
示例9: test_should_refresh
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import utcnow [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())
示例10: test_main_with_expiration_group
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import utcnow [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())
示例11: _handle_long_image_pulling
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import utcnow [as 别名]
def _handle_long_image_pulling(self, reason, pod):
"""
If pulling an image is taking long (1 minute) then return how many seconds
the pod ready state timeout should be extended by
Return value is an int that represents seconds
"""
# only apply once
if getattr(self, '_handle_long_image_pulling_applied', False):
return 0
if reason is not 'Pulling':
return 0
# last event should be Pulling in this case
event = self.events(pod).pop()
# see if pull operation has been happening for over 1 minute
seconds = 60 # time threshold before padding timeout
start = self.parse_date(event['firstTimestamp'])
if (start + timedelta(seconds=seconds)) < datetime.utcnow():
# make it so function doesn't do processing again
setattr(self, '_handle_long_image_pulling_applied', True)
return 600
return 0
示例12: _run_local_stream_event
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import utcnow [as 别名]
def _run_local_stream_event(table, table_action, new_item, old_item=None, context=None):
# if not running in lambda environment create event that normally results from dynamodb inserts and pass directly
# to the main lambda handler to simulate an event triggered by the dynamodb stream
if old_item is None:
old_item = {}
account = os.getenv(handlers.ENV_OPS_AUTOMATOR_ACCOUNT)
region = services.get_session().region_name
event = {
"Records": [
{
"eventName": table_action,
"eventSourceARN": "arn:aws:dynamodb:{}:{}:table/{}/stream/{}".format(region, account, table,
datetime.utcnow().isoformat()),
"eventSource": "aws:dynamodb",
"dynamodb": {
"NewImage": build_record(new_item),
"OldImage": build_record(old_item)
}
}]
}
handler = handlers.get_class_for_handler("TaskTrackingHandler")(event, context)
handler.handle_request()
示例13: __init__
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import utcnow [as 别名]
def __init__(self, event, context):
"""
Initializes the instance.
:param event: event to handle
:param context: CLambda context
"""
self._context = context
self._event = event
self._table = None
# Setup logging
classname = self.__class__.__name__
dt = datetime.utcnow()
logstream = LOG_STREAM.format(classname, dt.year, dt.month, dt.day)
self._logger = QueuedLogger(logstream=logstream, buffersize=50, context=context)
self.configuration_update = ScheduleHandler.is_config_update(self._event)
if self.configuration_update:
if "OldImage" in self._event["Records"][0]["dynamodb"]:
self.updated_task = self._event["Records"][0]["dynamodb"]["OldImage"][configuration.CONFIG_TASK_NAME]["S"]
else:
self.updated_task = self._event["Records"][0]["dynamodb"]["NewImage"][configuration.CONFIG_TASK_NAME]["S"]
self.execute_task_request = self.is_execute_event(self._event)
self.executed_task_name = event.get(handlers.HANDLER_EVENT_TASK_NAME, "") if self.execute_task_request else None
示例14: process_activity
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import utcnow [as 别名]
def process_activity(
self, activity: Activity, logic: Callable[[TurnContext], Awaitable]
):
self._conversation_lock.acquire()
try:
# ready for next reply
if activity.type is None:
activity.type = ActivityTypes.message
activity.channel_id = self.template.channel_id
activity.from_property = self.template.from_property
activity.recipient = self.template.recipient
activity.conversation = self.template.conversation
activity.service_url = self.template.service_url
activity.id = str((self._next_id))
self._next_id += 1
finally:
self._conversation_lock.release()
activity.timestamp = activity.timestamp or datetime.utcnow()
await self.run_pipeline(TurnContext(self, activity), logic)
示例15: create_activity_reply
# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import utcnow [as 别名]
def create_activity_reply(activity: Activity, text: str = None, locale: str = None):
"""Helper to create reply object."""
return Activity(
type=ActivityTypes.message,
timestamp=datetime.utcnow(),
from_property=ChannelAccount(
id=getattr(activity.recipient, "id", None),
name=getattr(activity.recipient, "name", None),
),
recipient=ChannelAccount(
id=activity.from_property.id, name=activity.from_property.name
),
reply_to_id=activity.id,
service_url=activity.service_url,
channel_id=activity.channel_id,
conversation=ConversationAccount(
is_group=activity.conversation.is_group,
id=activity.conversation.id,
name=activity.conversation.name,
),
text=text or "",
locale=locale or "",
attachments=[],
entities=[],
)