本文整理汇总了Python中datetime.utcnow方法的典型用法代码示例。如果您正苦于以下问题:Python datetime.utcnow方法的具体用法?Python datetime.utcnow怎么用?Python datetime.utcnow使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类datetime
的用法示例。
在下文中一共展示了datetime.utcnow方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: until_expiration
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import utcnow [as 别名]
def until_expiration(
expiry: Optional[str],
now: Optional[datetime.datetime] = None,
max_units: int = 2
) -> Optional[str]:
"""
Get the remaining time until infraction's expiration, in a human-readable version of the relativedelta.
Returns a human-readable version of the remaining duration between datetime.utcnow() and an expiry.
Unlike `humanize_delta`, this function will force the `precision` to be `seconds` by not passing it.
`max_units` specifies the maximum number of units of time to include (e.g. 1 may include days but not hours).
By default, max_units is 2.
"""
if not expiry:
return None
now = now or datetime.datetime.utcnow()
since = dateutil.parser.isoparse(expiry).replace(tzinfo=None, microsecond=0)
if since < now:
return None
return humanize_delta(relativedelta(since, now), max_units=max_units)
示例2: build_output_sas_url
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import utcnow [as 别名]
def build_output_sas_url(config, _blob_client):
"""
build a sas token for the output container
"""
sas_token = _blob_client.generate_container_shared_access_signature(
config.CONTAINER_NAME,
ContainerPermissions.READ
+ ContainerPermissions.WRITE
+ ContainerPermissions.DELETE
+ ContainerPermissions.LIST,
datetime.datetime.utcnow() + datetime.timedelta(hours=config.STORAGE_ACCESS_DURATION_HRS),
start=datetime.datetime.utcnow(),
)
_sas_url = "https://{}.blob.core.windows.net/{}?{}".format(
config.STORAGE_ACCOUNT_NAME, config.CONTAINER_NAME, sas_token
)
return _sas_url
示例3: set_last_updated
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import utcnow [as 别名]
def set_last_updated(self, time=None):
"""
Sets the last_updated field of the object being imported to time.
@arg time datetime object representing what last_updated should be set
to. Defaults to datetime.utcnow()
"""
if not hasattr(self.object, 'last_updated'):
return
last_updated = datetime.datetime.utcnow() if time is None else time
if self.object.last_updated != last_updated:
logger.info("Setting last_updated on %s to %s",
self.object, last_updated)
self.object.last_updated = last_updated
self.object.save()
示例4: exec_run
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import utcnow [as 别名]
def exec_run(self, cmd, stdout=True, stderr=True):
from datetime import datetime
_stdout = subprocess.PIPE if stdout else None
_stderr = subprocess.PIPE if stderr else None
result = subprocess.run(
cmd, stderr=_stderr, stdout=_stdout)
output = result.stdout if stdout else b''
output += result.stderr if stderr else b''
current_time = timestamp_to_seconds(
datetime.utcnow().isoformat() + 'Z')
duration = current_time - self.start_time
if duration > pip_checker.TIME_OUT:
result.returncode = 137
output = b''
return result.returncode, output
示例5: get_auth_parameters
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import utcnow [as 别名]
def get_auth_parameters(self, method, auth_path, expires, params=None, headers=None):
params = params or []
auth_params = [
("X-QS-Algorithm", "QS-HMAC-SHA256"),
("X-QS-Credential", self.qy_access_key_id),
("X-QS-Date", datetime.utcnow().strftime("%Y%m%dT%H%M%SZ")),
("X-QS-Expires", str(expires)),
]
signature = self._generate_signature(method, auth_path,
params + auth_params,
headers or {})
auth_params.append(("X-QS-Signature", signature))
return dict(auth_params)
示例6: stable_utcnow
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import utcnow [as 别名]
def stable_utcnow():
"""Returns a current datetime.utcnow() that doesn't change during a request.
You can use stable_utcnow to make sure that timedeltas computed against utcnow
in various areas of your code are consistent with each other without having to
inject an explicit datetime into each one.
Returns:
A datetime object that falls between the start of the current request and
live_utcnow(), and is the same on repeated calls during the same
request.
"""
# Environment variables are wiped between requests and module variables aren't
if not os.getenv(_STABLE_UTCNOW_ENV_MARKER_NAME, None):
SetStableUtcNowForTesting(live_utcnow())
return _stable_utcnow
示例7: mock_now
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import utcnow [as 别名]
def mock_now(dt):
"""Context manager for mocking out datetime.utcnow() in unit tests.
Example:
with mock_now(datetime.datetime(2011, 2, 3, 10, 11)):
assert datetime.datetime.utcnow() \
== datetime.datetime(2011, 2, 3, 10, 11)
"""
class MockDatetime(datetime.datetime):
@classmethod
def utcnow(cls):
return dt
real_datetime = datetime.datetime
datetime.datetime = MockDatetime
try:
yield datetime.datetime
finally:
datetime.datetime = real_datetime
示例8: dynamo_dump
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import utcnow [as 别名]
def dynamo_dump(self, value, *, context, **kwargs):
if value is None:
return None
if value.tzinfo is None:
raise ValueError(
"naive datetime instances are not supported. You can set a timezone with either "
"your_dt.replace(tzinfo=) or your_dt.astimezone(tz=). WARNING: calling astimezone on a naive "
"datetime will assume the naive datetime is in the system's timezone, even though "
"datetime.utcnow() creates a naive object! You almost certainly don't want to do that."
)
dt = value.astimezone(tz=datetime.timezone.utc)
return dt.strftime(FIXED_ISO8601_FORMAT)
示例9: time_since
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import utcnow [as 别名]
def time_since(past_datetime: datetime.datetime, precision: str = "seconds", max_units: int = 6) -> str:
"""
Takes a datetime and returns a human-readable string that describes how long ago that datetime was.
precision specifies the smallest unit of time to include (e.g. "seconds", "minutes").
max_units specifies the maximum number of units of time to include (e.g. 1 may include days but not hours).
"""
now = datetime.datetime.utcnow()
delta = abs(relativedelta(now, past_datetime))
humanized = humanize_delta(delta, precision, max_units)
return f"{humanized} ago"
示例10: wait_until
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import utcnow [as 别名]
def wait_until(time: datetime.datetime, start: Optional[datetime.datetime] = None) -> None:
"""
Wait until a given time.
:param time: A datetime.datetime object to wait until.
:param start: The start from which to calculate the waiting duration. Defaults to UTC time.
"""
delay = time - (start or datetime.datetime.utcnow())
delay_seconds = delay.total_seconds()
# Incorporate a small delay so we don't rapid-fire the event due to time precision errors
if delay_seconds > 1.0:
await asyncio.sleep(delay_seconds)
示例11: format_infraction_with_duration
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import utcnow [as 别名]
def format_infraction_with_duration(
date_to: Optional[str],
date_from: Optional[datetime.datetime] = None,
max_units: int = 2,
absolute: bool = True
) -> Optional[str]:
"""
Return `date_to` formatted as a readable ISO-8601 with the humanized duration since `date_from`.
`date_from` must be an ISO-8601 formatted timestamp. The duration is calculated as from
`date_from` until `date_to` with a precision of seconds. If `date_from` is unspecified, the
current time is used.
`max_units` specifies the maximum number of units of time to include in the duration. For
example, a value of 1 may include days but not hours.
If `absolute` is True, the absolute value of the duration delta is used. This prevents negative
values in the case that `date_to` is in the past relative to `date_from`.
"""
if not date_to:
return None
date_to_formatted = format_infraction(date_to)
date_from = date_from or datetime.datetime.utcnow()
date_to = dateutil.parser.isoparse(date_to).replace(tzinfo=None, microsecond=0)
delta = relativedelta(date_to, date_from)
if absolute:
delta = abs(delta)
duration = humanize_delta(delta, max_units=max_units)
duration_formatted = f" ({duration})" if duration else ""
return f"{date_to_formatted}{duration_formatted}"
示例12: check_transaction_hash
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import utcnow [as 别名]
def check_transaction_hash(self, tx_hash):
print('watching txn: {} at {}'.format(tx_hash, datetime.datetime.utcnow()))
tx_receipt = self.w3.eth.getTransactionReceipt(tx_hash)
def print_and_return(return_dict):
# Not printing here currently because the method above does it
# print('{} for txn: {}'.format(return_dict.get('status'), tx_hash))
return return_dict
if tx_receipt is None:
return print_and_return({'status': 'PENDING'})
mined_date = str(datetime.datetime.utcnow())
if tx_receipt.blockNumber is None:
return print_and_return({'status': 'PENDING', 'message': 'Next Block'})
if tx_receipt.status == 1:
return print_and_return({
'status': 'SUCCESS',
'block': tx_receipt.blockNumber,
'contract_address': tx_receipt.contractAddress,
'mined_date': mined_date
})
else:
return print_and_return({
'status': 'FAILED',
'error': 'Blockchain Error',
'block': tx_receipt.blockNumber,
'mined_date': mined_date
})
示例13: test_utcnow
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import utcnow [as 别名]
def test_utcnow(self):
import time
# Call it a success if utcnow() and utcfromtimestamp() are within
# a second of each other.
tolerance = timedelta(seconds=1)
for dummy in range(3):
from_now = self.theclass.utcnow()
from_timestamp = self.theclass.utcfromtimestamp(time.time())
if abs(from_timestamp - from_now) <= tolerance:
break
# Else try again a few times.
self.assertLessEqual(abs(from_timestamp - from_now), tolerance)
示例14: test_tzinfo_now
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import utcnow [as 别名]
def test_tzinfo_now(self):
meth = self.theclass.now
# Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
base = meth()
# Try with and without naming the keyword.
off42 = FixedOffset(42, "42")
another = meth(off42)
again = meth(tz=off42)
self.assertIs(another.tzinfo, again.tzinfo)
self.assertEqual(another.utcoffset(), timedelta(minutes=42))
# Bad argument with and w/o naming the keyword.
self.assertRaises(TypeError, meth, 16)
self.assertRaises(TypeError, meth, tzinfo=16)
# Bad keyword name.
self.assertRaises(TypeError, meth, tinfo=off42)
# Too many args.
self.assertRaises(TypeError, meth, off42, off42)
# We don't know which time zone we're in, and don't have a tzinfo
# class to represent it, so seeing whether a tz argument actually
# does a conversion is tricky.
weirdtz = FixedOffset(timedelta(hours=15, minutes=58), "weirdtz", 0)
utc = FixedOffset(0, "utc", 0)
for dummy in range(3):
now = datetime.now(weirdtz)
self.assertIs(now.tzinfo, weirdtz)
utcnow = datetime.utcnow().replace(tzinfo=utc)
now2 = utcnow.astimezone(weirdtz)
if abs(now - now2) < timedelta(seconds=30):
break
# Else the code is broken, or more than 30 seconds passed between
# calls; assuming the latter, just try again.
else:
# Three strikes and we're out.
self.fail("utcnow(), now(tz), or astimezone() may be broken")
示例15: test_tzinfo_utcnow
# 需要导入模块: import datetime [as 别名]
# 或者: from datetime import utcnow [as 别名]
def test_tzinfo_utcnow(self):
meth = self.theclass.utcnow
# Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
base = meth()
# Try with and without naming the keyword; for whatever reason,
# utcnow() doesn't accept a tzinfo argument.
off42 = FixedOffset(42, "42")
self.assertRaises(TypeError, meth, off42)
self.assertRaises(TypeError, meth, tzinfo=off42)