当前位置: 首页>>代码示例>>Python>>正文


Python datetime.isoformat方法代码示例

本文整理汇总了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 
开发者ID:hyperledger,项目名称:indy-node,代码行数:25,代码来源:test_broken_connection_control_tool.py

示例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) 
开发者ID:hyperledger,项目名称:indy-node,代码行数:24,代码来源:test_pool_restart.py

示例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}) 
开发者ID:industrydive,项目名称:fileflow,代码行数:18,代码来源:test_taskRunner.py

示例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() 
开发者ID:openai,项目名称:kubernetes-ec2-autoscaler,代码行数:25,代码来源:test_cluster.py

示例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() 
开发者ID:openai,项目名称:kubernetes-ec2-autoscaler,代码行数:23,代码来源:test_cluster.py

示例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 
开发者ID:eavatar,项目名称:eavatar-me,代码行数:19,代码来源:webapi.py

示例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)) 
开发者ID:karlicoss,项目名称:promnesia,代码行数:25,代码来源:py37.py

示例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 
开发者ID:regit,项目名称:pshitt,代码行数:27,代码来源:pshitt.py

示例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
    } 
开发者ID:SPARLab,项目名称:BikeMaps,代码行数:39,代码来源:weather.py

示例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) 
开发者ID:ClusterHQ,项目名称:flocker,代码行数:10,代码来源:cleanup.py

示例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.') 
开发者ID:zulip,项目名称:zulip,代码行数:16,代码来源:add_users_to_mailing_list.py

示例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)) 
开发者ID:JohannesEbke,项目名称:aws_list_all,代码行数:38,代码来源:query.py

示例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) 
开发者ID:hyperledger,项目名称:indy-node,代码行数:16,代码来源:test_pool_upgrade_same_time_different_days.py

示例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') 
开发者ID:hyperledger,项目名称:indy-node,代码行数:17,代码来源:conftest.py

示例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 
开发者ID:hyperledger,项目名称:indy-node,代码行数:16,代码来源:conftest.py


注:本文中的datetime.datetime.isoformat方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。