本文整理匯總了Python中datetime.datetime.isoformat方法的典型用法代碼示例。如果您正苦於以下問題:Python datetime.isoformat方法的具體用法?Python datetime.isoformat怎麽用?Python datetime.isoformat使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類datetime.datetime
的用法示例。
在下文中一共展示了datetime.isoformat方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_node_doesnt_retry_upgrade
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import isoformat [as 別名]
def test_node_doesnt_retry_upgrade(looper, nodeSet, validUpgrade, nodeIds,
sdk_pool_handle, sdk_wallet_trustee, tconf,
skip_functions):
schedule = {}
unow = datetime.utcnow().replace(tzinfo=dateutil.tz.tzutc())
startAt = unow + timedelta(seconds=delta)
for i in nodeIds:
schedule[i] = datetime.isoformat(startAt)
startAt = startAt + timedelta(seconds=delta)
validUpgrade['schedule'] = schedule
# Emulating connection problems
for node in nodeSet:
node.upgrader.retry_limit = 0
# Send upgrade
sdk_ensure_upgrade_sent(looper, sdk_pool_handle,
sdk_wallet_trustee, validUpgrade)
looper.runFor(len(nodeIds) * delta)
# Every node, including bad_node, tried to upgrade only once
for node in nodeSet:
assert node.upgrader.spylog.count(Upgrader.processLedger.__name__) == 1
示例2: test_pool_restart
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import isoformat [as 別名]
def test_pool_restart(
sdk_pool_handle, sdk_wallet_trustee, looper, tconf, txnPoolNodeSet):
server, indicator = looper.loop.run_until_complete(
_createServer(
host=tconf.controlServiceHost,
port=tconf.controlServicePort
)
)
unow = datetime.utcnow().replace(tzinfo=dateutil.tz.tzutc())
start_at = unow + timedelta(seconds=1000)
req_obj, responses = sdk_send_restart(looper,
sdk_wallet_trustee,
sdk_pool_handle,
action=START,
datetime=str(datetime.isoformat(start_at)))
_stopServer(server)
for node in txnPoolNodeSet:
assert node.restarter.lastActionEventInfo.ev_type == RestartLog.Events.scheduled
_comparison_reply(responses, req_obj)
示例3: test_write_timestamp_file
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import isoformat [as 別名]
def test_write_timestamp_file(self, mock_dt):
"""
Assert a TaskRunner calls write_json with the expected args. Implicitly testing that we are using datetime.isoformat to derive
the value for the "RUN" key.
:param mock_dt: ??? not sure this patch is necessary
"""
fake_date_str = "not iso formatted"
mock_datetime_obj = mock.MagicMock()
mock_datetime_obj.isoformat = mock.MagicMock(return_value=fake_date_str)
mock_dt.datetime.now = mock.MagicMock(return_value=mock_datetime_obj)
self.task_runner_instance.write_json = mock.MagicMock()
self.task_runner_instance.write_timestamp_file()
self.task_runner_instance.write_json.assert_called_once_with({'RUN': fake_date_str})
示例4: test_reap_dead_node
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import isoformat [as 別名]
def test_reap_dead_node(self):
node = copy.deepcopy(self.dummy_node)
TestInstance = collections.namedtuple('TestInstance', ['launch_time'])
instance = TestInstance(datetime.now(pytz.utc))
ready_condition = None
for condition in node['status']['conditions']:
if condition['type'] == 'Ready':
ready_condition = condition
break
ready_condition['status'] = 'Unknown'
ready_condition['lastHeartbeatTime'] = datetime.isoformat(datetime.now(pytz.utc) - timedelta(minutes=30))
kube_node = KubeNode(pykube.Node(self.api, node))
kube_node.delete = mock.Mock(return_value="mocked stuff")
self.cluster.maintain([kube_node], {kube_node.instance_id: instance}, {}, [], [])
kube_node.delete.assert_not_called()
ready_condition['lastHeartbeatTime'] = datetime.isoformat(datetime.now(pytz.utc) - timedelta(hours=2))
kube_node = KubeNode(pykube.Node(self.api, node))
kube_node.delete = mock.Mock(return_value="mocked stuff")
self.cluster.maintain([kube_node], {kube_node.instance_id: instance}, {}, [], [])
kube_node.delete.assert_called_once_with()
示例5: test_max_scale_in
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import isoformat [as 別名]
def test_max_scale_in(self):
node1 = copy.deepcopy(self.dummy_node)
node2 = copy.deepcopy(self.dummy_node)
TestInstance = collections.namedtuple('TestInstance', ['launch_time'])
instance1 = TestInstance(datetime.now(pytz.utc))
instance2 = TestInstance(datetime.now(pytz.utc))
for node in [node1, node2]:
for condition in node['status']['conditions']:
if condition['type'] == 'Ready':
condition['status'] = 'Unknown'
condition['lastHeartbeatTime'] = datetime.isoformat(datetime.now(pytz.utc) - timedelta(hours=2))
break
kube_node1 = KubeNode(pykube.Node(self.api, node1))
kube_node1.delete = mock.Mock(return_value="mocked stuff")
kube_node2 = KubeNode(pykube.Node(self.api, node2))
kube_node2.delete = mock.Mock(return_value="mocked stuff")
self.cluster.maintain([kube_node1, kube_node2], {kube_node1.instance_id: instance1, kube_node2.instance_id: instance2}, {}, [], [])
kube_node1.delete.assert_not_called()
kube_node2.delete.assert_not_called()
示例6: log_list
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import isoformat [as 別名]
def log_list():
entries = []
i = 1
for it in log.recent_log_entries():
isotime = datetime.isoformat(it.time)
if hasattr(it, 'message'):
msg = it.message
else:
msg = ''
rec = dict(id=i, msg=msg, lvl=it.levelno, ts=isotime)
entries.append(rec)
i += 1
return dict(data=entries, status=defines.SUCCESS)
# jobs
示例7: fromisoformat
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import isoformat [as 別名]
def fromisoformat(date_string, cls=datetime):
"""Construct a datetime from the output of datetime.isoformat()."""
if not isinstance(date_string, str):
raise TypeError('fromisoformat: argument must be str')
# Split this at the separator
dstr = date_string[0:10]
tstr = date_string[11:]
try:
date_components = _parse_isoformat_date(dstr)
except ValueError:
raise ValueError('Invalid isoformat string: %s' % date_string)
if tstr:
try:
time_components = _parse_isoformat_time(tstr)
except ValueError:
raise ValueError('Invalid isoformat string: %s' % date_string)
else:
time_components = [0, 0, 0, 0, None]
return cls(*(date_components + time_components))
示例8: check_auth_password
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import isoformat [as 別名]
def check_auth_password(self, username, password):
data = {}
data['username'] = username
data['password'] = password
if self.addr.startswith('::ffff:'):
data['src_ip'] = self.addr.replace('::ffff:', '')
else:
data['src_ip'] = self.addr
data['src_port'] = self.port
data['timestamp'] = datetime.isoformat(datetime.utcnow())
try:
rversion = self.transport.remote_version.split('-', 2)[2]
data['software_version'] = rversion
except Exception:
data['software_version'] = self.transport.remote_version
pass
data['cipher'] = self.transport.remote_cipher
data['mac'] = self.transport.remote_mac
data['try'] = self.count
self.count += 1
logging.debug("%s:%d tried username '%s' with '%s'" %
(self.addr, self.port, username, password))
self.logfile.write(json.dumps(data) + '\n')
self.logfile.flush()
return paramiko.AUTH_FAILED
示例9: get_weather
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import isoformat [as 別名]
def get_weather(coords, date):
""" Generate a dict of weather data for a location at a given time
Keyword arguments:
coords -- decimal degree coordinates of location. Format is [longitude, latitude]
date -- a python datetime object
"""
(lng, lat) = coords
DIRECTIONS = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]
# A call is made to the API using the provided key
APIkey = settings.FORECAST_IO_API_KEY
physicalURL = "https://api.forecast.io/forecast/"+APIkey+"/"+str(lat)+","+str(lng)+","+datetime.isoformat(date)+"?units=ca"
response = json.loads( urllib2.urlopen(physicalURL).read() )
c = response['currently']
d = response['daily']['data'][0]
sunrise = d.get('sunriseTime', None)
sunset = d.get('sunsetTime', None)
return {
'summary': c.get('summary', ''),
'sunrise_time': datetime.utcfromtimestamp(sunrise + response['offset']*60*60) if sunrise else None,
'sunset_time': datetime.utcfromtimestamp(sunset + response['offset']*60*60) if sunset else None,
'dawn': (sunrise-30*60 <= time.mktime(date.timetuple()) <= sunrise) if sunrise else False,
'dusk': (sunset <= time.mktime(date.timetuple()) <= sunrise+30*60) if sunrise else False,
'precip_intensity': c.get('precipIntensity', -1),
'precip_probability': c.get('precipProbability', -1),
'precip_type': c.get('precipType', ""),
'temperature': c.get('temperature', -1),
'black_ice_risk': c.get('temperature', 100) <= -18 or (c.get('precipIntensity', -1) > 0 and c.get('temperature', 100) <= 0),
'wind_speed': c.get('windSpeed', -1),
'wind_bearing': c.get('windBearing', -1),
'wind_bearing_str': DIRECTIONS[int((c.get('windBearing') + 22.5) // 45 % 8)] if c.get('windBearing') else "",
'visibility_km': c.get('visibility', -1), # if visibilityKM == 16.09 it is unlimited
}
示例10: _format_time
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import isoformat [as 別名]
def _format_time(when):
"""
Format a time to ISO8601 format. Or if there is no time, just return
``None``.
"""
if when is None:
return None
return datetime.isoformat(when)
示例11: add_arguments
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import isoformat [as 別名]
def add_arguments(self, parser: argparse.ArgumentParser) -> None:
parser.add_argument('--api-key',
dest='api_key',
type=str,
help='MailChimp API key.')
parser.add_argument('--list-id',
dest='list_id',
type=str,
help='List ID of the MailChimp mailing list.')
parser.add_argument('--optin-time',
dest='optin_time',
type=str,
default=datetime.isoformat(timezone_now().replace(microsecond=0)),
help='Opt-in time of the users.')
示例12: acquire_listing
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import isoformat [as 別名]
def acquire_listing(verbose, what):
"""Given a service, region and operation execute the operation, serialize and save the result and
return a tuple of strings describing the result."""
service, region, operation = what
try:
if verbose > 1:
print(what, 'starting request...')
listing = Listing.acquire(service, region, operation)
if verbose > 1:
print(what, '...request successful.')
if listing.resource_total_count > 0:
with open('{}_{}_{}.json'.format(service, operation, region), 'w') as jsonfile:
json.dump(listing.to_json(), jsonfile, default=datetime.isoformat)
return (RESULT_SOMETHING, service, region, operation, ', '.join(listing.resource_types))
else:
return (RESULT_NOTHING, service, region, operation, ', '.join(listing.resource_types))
except Exception as exc: # pylint:disable=broad-except
if verbose > 1:
print(what, '...exception:', exc)
if verbose > 2:
print_exc()
result_type = RESULT_NO_ACCESS if 'AccessDeniedException' in str(exc) else RESULT_ERROR
ignored_err = RESULT_IGNORE_ERRORS.get(service, {}).get(operation)
if ignored_err is not None:
if not isinstance(ignored_err, list):
ignored_err = list(ignored_err)
for ignored_str_err in ignored_err:
if ignored_str_err in str(exc):
result_type = RESULT_NOTHING
for not_available_string in NOT_AVAILABLE_STRINGS:
if not_available_string in str(exc):
result_type = RESULT_NOTHING
return (result_type, service, region, operation, repr(exc))
示例13: test_pool_upgrade_same_time_different_days
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import isoformat [as 別名]
def test_pool_upgrade_same_time_different_days(looper, tconf, nodeSet,
validUpgrade, sdk_pool_handle,
sdk_wallet_trustee, nodeIds):
day_in_sec = 24 * 60 * 60
upgr1 = deepcopy(validUpgrade)
schedule = {}
unow = datetime.utcnow().replace(tzinfo=dateutil.tz.tzutc())
startAt = unow + timedelta(seconds=day_in_sec)
for i in nodeIds:
schedule[i] = datetime.isoformat(startAt)
startAt = startAt + timedelta(seconds=day_in_sec)
upgr1['schedule'] = schedule
sdk_ensure_upgrade_sent(looper, sdk_pool_handle, sdk_wallet_trustee, upgr1)
示例14: validUpgrade
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import isoformat [as 別名]
def validUpgrade(nodeIds, tconf, monkeypatch, pckg):
schedule = {}
unow = datetime.utcnow().replace(tzinfo=dateutil.tz.tzutc())
startAt = unow + timedelta(seconds=100)
acceptableDiff = tconf.MinSepBetweenNodeUpgrades + 1
for i in nodeIds:
schedule[i] = datetime.isoformat(startAt)
startAt = startAt + timedelta(seconds=acceptableDiff + 3)
new_version = bumpedVersion(pckg[1])
patch_packet_mgr_output(monkeypatch, pckg[0], pckg[1], new_version)
return dict(name='upgrade-{}'.format(randomText(3)), version=new_version,
action=START, schedule=schedule, timeout=1, package=pckg[0],
sha256='db34a72a90d026dae49c3b3f0436c8d3963476c77468ad955845a1ccf7b03f55')
示例15: invalidUpgrade
# 需要導入模塊: from datetime import datetime [as 別名]
# 或者: from datetime.datetime import isoformat [as 別名]
def invalidUpgrade(nodeIds, tconf, validUpgrade):
nup = validUpgrade.copy()
schedule = {}
unow = datetime.utcnow().replace(tzinfo=dateutil.tz.tzutc())
startAt = unow + timedelta(seconds=60)
acceptableDiff = tconf.MinSepBetweenNodeUpgrades + 1
for i in nodeIds:
schedule[i] = datetime.isoformat(startAt)
startAt = startAt + timedelta(seconds=acceptableDiff - 3)
nup.update(dict(name='upgrade-14', version=bumpedVersion(), action=START,
schedule=schedule,
sha256='46c715a90b1067142d548cb1f1405b0486b32b1a27d418ef3a52bd976e9fae50',
timeout=10))
return nup