Python datetime.datetime.isoformat() Examples

The following are code examples for showing how to use datetime.datetime.isoformat(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: bqup   Author: thinkingmachines   File: main.py    MIT License 6 votes vote down vote up
def main():

    args = docopt(__doc__)

    target_dir = args['--dir'] or datetime.isoformat(datetime.now())
    force = args['--force']

    if (not force) and os.path.exists(target_dir):
        print("Target directory already exists. Consider running with -f.")
        exit()

    project_id = args['--project']
    print("Loading {}...".format(project_id or "default project"))
    p = Project(project_id or None, args['--schema'])

    if args['--verbose']:
        p.print()

    print("Loaded {}.".format(p.project_id))

    print("Exporting {} to {}...".format(p.project_id, target_dir))
    p.export(target_dir, force=force)
    print("Project {} exported to {}.".format(p.project_id, target_dir)) 
Example 2
Project: indy-node   Author: hyperledger   File: test_broken_connection_control_tool.py    Apache License 2.0 6 votes vote down vote up
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 
Example 3
Project: indy-node   Author: hyperledger   File: test_pool_restart.py    Apache License 2.0 6 votes vote down vote up
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) 
Example 4
Project: fileflow   Author: industrydive   File: test_taskRunner.py    Apache License 2.0 6 votes vote down vote up
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}) 
Example 5
Project: azurectl   Author: SUSE-Enceladus   File: instance_data_disk_test.py    Apache License 2.0 6 votes vote down vote up
def test_create(self, mock_storage, mock_datetime):
        self.service.add_disk.return_value = self.my_request
        mock_datetime.isoformat.return_value = '0'
        time_now = mock.Mock()
        time_now.strftime.return_value = 1471858765
        mock_datetime.now = mock.Mock(
            return_value=time_now
        )
        result = self.data_disk.create(
            identifier=self.instance_name,
            disk_size_in_gb=self.disk_size,
            label=self.disk_label
        )
        mock_storage.assert_called_once_with(
            self.account, self.account.storage_container()
        )
        self.service.add_disk.assert_called_once_with(
            media_link=self.disk_url,
            name=self.data_disk.data_disk_name.replace('.vhd', ''),
            label=self.disk_label,
            has_operating_system=False,
            os='Linux',
        ) 
Example 6
Project: azurectl   Author: SUSE-Enceladus   File: instance_data_disk_test.py    Apache License 2.0 6 votes vote down vote up
def test_attach_without_lun(self, mock_datetime):
        # mock no data disks attached has to result in lun 0 assigned later
        self.service.get_data_disk.side_effect = AzureMissingResourceHttpError(
            'NOT FOUND', 404
        )
        mock_datetime.isoformat.return_value = '0'
        self.service.add_data_disk.return_value = self.my_request
        result = self.data_disk.attach(
            self.disk_name,
            self.cloud_service_name
        )
        self.service.add_data_disk.assert_called_once_with(
            self.cloud_service_name,
            self.cloud_service_name,
            self.cloud_service_name,
            0,
            disk_name=self.disk_name
        ) 
Example 7
Project: kubernetes-ec2-autoscaler   Author: openai   File: test_cluster.py    MIT License 6 votes vote down vote up
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() 
Example 8
Project: kubernetes-ec2-autoscaler   Author: openai   File: test_cluster.py    MIT License 6 votes vote down vote up
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() 
Example 9
Project: eavatar-me   Author: eavatar   File: webapi.py    Apache License 2.0 6 votes vote down vote up
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 
Example 10
Project: haydi   Author: spirali   File: xenv.py    MIT License 6 votes vote down vote up
def run(self, action, write=False, **kwargs):
        config = {name: self.config_dict[name] for name in self.config_names}
        print "Configuration"
        for name in self.config_names:
            print "\t{}: {}".format(name, config[name])
        print "Time:", self.time

        results = action.run(self.ctx, timeout=self.time, **kwargs)
        if write:
            filename = "{}-{}.data".format(
                self.name, datetime.isoformat(datetime.now()))
            print "Writing results into {}".format(filename)
            with open(filename, "w") as f:
                pickle.dump(config, f)
                pickle.dump(results, f)
        return results 
Example 11
Project: Loosindus   Author: TaaviE   File: utility_standalone.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def get_timestamp() -> str:
    """
    Returns the current timestamp
    """
    return str(datetime.isoformat(datetime.now())) 
Example 12
Project: squeakspace   Author: eek6   File: _util.py    GNU General Public License v3.0 5 votes vote down vote up
def _now():
    """Get a timestamp for right now, formatted according to ISO 8601."""
    return datetime.isoformat(datetime.now()) 
Example 13
Project: blockstore   Author: open-craft   File: store.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def parse_utc_iso8601_datetime(datetime_str):
    """
    Create a UTC datetime from a str generated by calling datetime.isoformat()

    Python's datetime module is incapable of parsing the ISO 8601 string output
    that it itself produces (it can't do timezones with ":" in them), so we need
    to only parse the part before that and then manually add UTC timezone
    information into it. This is a hack -- it will ignore whatever timezone is
    really there and force it to be interpreted as UTC.

    This hack should not be necessary once we move to Python 3.7 and can be
    replaced with datetime.fromisoformat().
    """
    parsed_dt = datetime.strptime(datetime_str, r'%Y-%m-%dT%H:%M:%S.%f+00:00')
    return pytz.utc.localize(parsed_dt).astimezone(timezone.utc) 
Example 14
Project: volttron-applications   Author: VOLTTRON   File: builders.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def build_event_descriptor(site_event):
        event_id = site_event.dr_event.event_id
        modification_number = site_event.dr_event.modification_number

        modification_reason = None
        priority = 1
        test_event = False
        vtn_comment = None

        created_date_time = datetime.isoformat(datetime.now())
        created_date_time = created_date_time[0:-7]

        event_status = 'far'
        if site_event.status == 'cancelled' or site_event.status == 'CANCELED':
            event_status = 'cancelled'
        else:
            event_status = site_event.dr_event.status

        return oadr_20b.eventDescriptorType(eventID=event_id,
                                            modificationNumber=modification_number,
                                            modificationReason=modification_reason,
                                            priority=priority,
                                            createdDateTime=created_date_time,
                                            eventStatus=event_status,
                                            testEvent=test_event,
                                            vtnComment=vtn_comment) 
Example 15
Project: zulip   Author: zulip   File: add_users_to_mailing_list.py    Apache License 2.0 5 votes vote down vote up
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.') 
Example 16
Project: shadowsocks   Author: bluekittencloud   File: _util.py    Apache License 2.0 5 votes vote down vote up
def _now():
    """Get a timestamp for right now, formatted according to ISO 8601."""
    return datetime.isoformat(datetime.now()) 
Example 17
Project: aws_list_all   Author: JohannesEbke   File: query.py    MIT License 5 votes vote down vote up
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)) 
Example 18
Project: indy-node   Author: hyperledger   File: test_pool_upgrade_same_time_different_days.py    Apache License 2.0 5 votes vote down vote up
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) 
Example 19
Project: indy-node   Author: hyperledger   File: conftest.py    Apache License 2.0 5 votes vote down vote up
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') 
Example 20
Project: indy-node   Author: hyperledger   File: conftest.py    Apache License 2.0 5 votes vote down vote up
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 
Example 21
Project: indy-node   Author: hyperledger   File: test_state_recovering.py    Apache License 2.0 5 votes vote down vote up
def valid_upgrade(nodeSet, tconf):
    schedule = {}
    unow = datetime.utcnow().replace(tzinfo=dateutil.tz.tzutc())
    startAt = unow + timedelta(seconds=30000000)
    acceptableDiff = tconf.MinSepBetweenNodeUpgrades + 1
    for n in nodeSet[0].poolManager.nodeIds:
        schedule[n] = datetime.isoformat(startAt)
        startAt = startAt + timedelta(seconds=acceptableDiff + 3)

    return dict(name='upgrade', version="10000.10.10",
                action=START, schedule=schedule, timeout=1,
                package=None,
                sha256='db34a72a90d026dae49c3b3f0436c8d3963476c77468ad955845a1ccf7b03f55') 
Example 22
Project: indy-node   Author: hyperledger   File: test_pool_restart.py    Apache License 2.0 5 votes vote down vote up
def test_pool_restart_cancel(
        sdk_pool_handle, sdk_wallet_trustee, looper, tconf, txnPoolNodeSet):
    loop = asyncio.get_event_loop()
    server, indicator = 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)))
    for node in txnPoolNodeSet:
        assert node.restarter.lastActionEventInfo.ev_type == RestartLog.Events.scheduled
    _comparison_reply(responses, req_obj)

    req_obj, responses = sdk_send_restart(looper,
                                          sdk_wallet_trustee,
                                          sdk_pool_handle,
                                          action=CANCEL,
                                          datetime="")
    _stopServer(server)
    for node in txnPoolNodeSet:
        assert node.restarter.lastActionEventInfo.ev_type == RestartLog.Events.cancelled
    _comparison_reply(responses, req_obj) 
Example 23
Project: indy-node   Author: hyperledger   File: test_pool_restart.py    Apache License 2.0 5 votes vote down vote up
def _check_restart_log(item, action, when=None):
    assert item.ev_type == action and (
            when is None or str(datetime.isoformat(item.data.when)) == when) 
Example 24
Project: indy-node   Author: hyperledger   File: test_pool_restarts_one_by_one_with_restart_now.py    Apache License 2.0 5 votes vote down vote up
def test_pool_restarts_one_by_one_with_restart_now(
        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())
    first_start = str(datetime.isoformat(unow + timedelta(seconds=1000)))
    req_obj, resp = sdk_send_restart(looper,
                                     sdk_wallet_trustee,
                                     sdk_pool_handle,
                                     action=START,
                                     datetime=first_start)
    _comparison_reply(resp, req_obj)
    second_start = "0"
    req_obj, resp = sdk_send_restart(looper,
                                     sdk_wallet_trustee,
                                     sdk_pool_handle,
                                     action=START,
                                     datetime=second_start)
    _comparison_reply(resp, req_obj)
    restart_log = []
    for a in txnPoolNodeSet[0].restarter._actionLog:
        restart_log.append(a)
    restart_log.reverse()
    _check_restart_log(restart_log[1], RestartLog.Events.scheduled, first_start)
    _check_restart_log(restart_log[0], RestartLog.Events.cancelled)
    _stopServer(server) 
Example 25
Project: indy-node   Author: hyperledger   File: test_auth_rule_using.py    Apache License 2.0 5 votes vote down vote up
def validUpgrade(self, nodeIds, tconf, pckg, monkeymodule):
        schedule = {}
        unow = datetime.utcnow().replace(tzinfo=dateutil.tz.tzutc())
        startAt = unow + timedelta(seconds=3000)
        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(monkeymodule, 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') 
Example 26
Project: pywikiapi   Author: nyurik   File: utils.py    MIT License 5 votes vote down vote up
def to_timestamp(value):
    """
    Convert datetime to a timestamp string MediaWiki would understand.
    :type value: datetime
    :rtype str
    """
    # datetime.isoformat() wouldn't work because it sometimes produces +00:00 that MW does not support
    # Also perform sanity check here to make sure this is a UTC time
    if value.tzinfo is not None and value.tzinfo.utcoffset(value):
        raise ValueError('datetime value has a non-UTC timezone')
    return value.strftime('%Y-%m-%dT%H:%M:%SZ') 
Example 27
Project: mlpipeline   Author: ahmed-shariff   File: _pipeline_subprocess.py    MIT License 5 votes vote down vote up
def _save_results_to_file(resultString, experiment):
    modified_dt = datetime.isoformat(datetime.fromtimestamp(
        CONFIG.executed_experiments[experiment.name].modified_time))
    result_dt = datetime.now().isoformat()

    with open(CONFIG.output_file, 'a', encoding="utf-8") as outfile:
        outfile.write("\n[{0}]:ml-pipline: output: \n".format(result_dt))
        outfile.write(resultString)
    with open(CONFIG.history_file, 'a', encoding="utf-8") as hist_file:
        hist_file.write("{0}::{1}::{2}\n".format(
            experiment.name,
            CONFIG.executed_experiments[experiment.name].modified_time,
            CONFIG.executed_experiments[experiment.name].version.executing_version))

    CONFIG.executed_experiments[experiment.name].version.moveExecutingToExecuted() 
Example 28
Project: content   Author: demisto   File: PagerDuty.py    MIT License 5 votes vote down vote up
def fetch_incidents():
    param_dict = {}
    now_time = datetime.utcnow()
    now = datetime.isoformat(now_time)
    lastRunObject = demisto.getLastRun()
    if lastRunObject:
        param_dict['since'] = lastRunObject['time']
    else:
        param_dict['since'] = datetime.isoformat(now_time - timedelta(minutes=int(FETCH_INTERVAL)))

    param_dict['until'] = now

    url = SERVER_URL + GET_INCIDENTS_SUFFIX + configure_status()
    res = http_request('GET', url, param_dict)
    _, parsed_incidents, raw_responses = parse_incident_data(res.get('incidents', []))

    incidents = []
    for incident, raw_response in zip(parsed_incidents, raw_responses):
        incidents.append({
            'name': incident['ID'] + ' - ' + incident['Title'],
            'occurred': incident['created_at'],
            'severity': translate_severity(incident['urgency']),
            'rawJSON': json.dumps(raw_response)
        })

    demisto.incidents(incidents)
    demisto.setLastRun({'time': now}) 
Example 29
Project: garage   Author: clchiou   File: datetimes.py    MIT License 5 votes vote down vote up
def format_iso8601(dt_obj):
    # datetime.isoformat() would generate a ':' in the time zone, which
    # datetime.strptime cannot parse :(
    # So use datetime.strftime(DATETIME_FORMAT) here.
    return dt_obj.strftime(DATETIME_FORMAT) 
Example 30
Project: mycroft   Author: Yelp   File: pipeline.py    MIT License 5 votes vote down vote up
def mk_log_msg(tag, data):
        """A uniform log message in JSON format"""
        return simplejson.dumps({
            # fields starting with _ will appear after @timestamp
            '@timestamp': datetime.isoformat(datetime.utcnow()),
            '_hostname': LogMsgFormatter.hostname,
            '_pid': LogMsgFormatter.pid,
            'msg': data,
            'tag': tag,
        }, sort_keys=True) 
Example 31
Project: shadowsocks   Author: PaperDashboard   File: _util.py    Apache License 2.0 5 votes vote down vote up
def _now():
    """Get a timestamp for right now, formatted according to ISO 8601."""
    return datetime.isoformat(datetime.now()) 
Example 32
Project: niworkflows   Author: poldracklab   File: conftest.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _run_interface_mock(objekt, runtime):
    runtime.returncode = 0
    runtime.endTime = dt.isoformat(dt.utcnow())

    objekt._out_report = os.path.abspath(objekt.inputs.out_report)
    objekt._post_run_hook(runtime)
    objekt._generate_report()
    return runtime 
Example 33
Project: flask-real-time-map   Author: hedderich   File: test_api.py    MIT License 5 votes vote down vote up
def update_location(client, vehicle_id, lat, lng):
    now = datetime.isoformat(datetime.utcnow())
    return client.post('/vehicles/%s/locations' % vehicle_id,
                       data=json.dumps({'lat': lat,
                                        'lng': lng,
                                        'at': now}),
                       content_type='application/json') 
Example 34
Project: TripletEmbedding   Author: hrantzsch   File: logger.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, args, optimizer, name, extra_msg=''):
        self.iteration = 0
        self.sum_loss = 0
        self.sum_acc = 0
        self.sum_mean_diff = 0
        self.sum_max_diff = 0
        self.current_section = ''
        self.optimizer = optimizer

        # setup according to arguments
        self.name = name if name is not '' else 'signdist'
        self.out_file = "{}_{}".format(date.isoformat(date.today()), self.name)
        self.log_file = "{}.log".format(self.out_file)
        # write config to head of the log file
        self.write_config(args, extra_msg) 
Example 35
Project: TripletEmbedding   Author: hrantzsch   File: logger.py    GNU General Public License v3.0 5 votes vote down vote up
def write_config(self, args, extra_msg):
        with open(self.log_file, 'a+') as f:
            self._comment("=" * 40, f)
            self._comment("{} initiated at {}".format(
                self.name, datetime.isoformat(datetime.now())
            ), f)
            self._comment("-" * 40, f)  # arguments passed
            self._comment("Data: " + args.data, f)
            self._comment("Batchsize: {}".format(args.batchsize), f)
            self._comment("Test ratio: {}".format(args.test), f)
            self._comment("Hard triplet ratio: {}".format(args.skilled), f)
            dev = "CPU" if args.gpu < 0 else "GPU ".format(args.gpu)
            self._comment("Device: " + dev, f)
            if args.initmodel:
                self._comment("Init model: " + args.initmodel, f)
            if args.resume:
                self._comment("Resume state: " + args.resume, f)
            self._comment("-" * 40, f)  # parameters set in script
            self._comment("Optimizer: " + self.optimizer.__class__.__name__, f)
            self._comment("Initial LR: {}".format(self.optimizer.lr), f)
            self._comment("LR interval: {}".format(args.lrinterval), f)
            self._comment("Weight decay: {}".format(args.weight_decay), f)
            self._comment("Epoch: {}".format(self.optimizer.epoch), f)
            if extra_msg:
                self._comment(extra_msg, f)
            self._comment("-" * 40, f)  # complete call
            self._comment("{}".format(sys.argv), f)
            self._comment("=" * 40, f) 
Example 36
Project: bouncy-sink   Author: SparkPost   File: webReporter.py    Apache License 2.0 5 votes vote down vote up
def timeStr(t):
    utc = datetime.fromtimestamp(t, timezone.utc)
    return datetime.isoformat(utc, sep='T', timespec='seconds') 
Example 37
Project: pipelines   Author: gis-rpd   File: utils.py    MIT License 5 votes vote down vote up
def generate_timestamp():
    """generate ISO8601 timestamp incl microsends, but with colons
    replaced to avoid problems if used as file name
    """
    return datetime.isoformat(datetime.now()).replace(":", "-") 
Example 38
Project: old-sovrin   Author: sovrin-foundation   File: conftest.py    Apache License 2.0 5 votes vote down vote up
def validUpgrade(nodeIds, tconf):
    schedule = {}
    unow = datetime.utcnow().replace(tzinfo=dateutil.tz.tzutc())
    startAt = unow + timedelta(seconds=90)
    acceptableDiff = tconf.MinSepBetweenNodeUpgrades + 1
    for i in nodeIds:
        schedule[i] = datetime.isoformat(startAt)
        startAt = startAt + timedelta(seconds=acceptableDiff + 3)
    return dict(name='upgrade-13', version=bumpedVersion(), action=START,
                schedule=schedule, sha256='aad1242', timeout=10) 
Example 39
Project: old-sovrin   Author: sovrin-foundation   File: test_pool_upgrade.py    Apache License 2.0 5 votes vote down vote up
def invalidUpgrade(nodeIds, tconf):
    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)

    return dict(name='upgrade-14', version=bumpedVersion(), action=START,
                schedule=schedule, sha256='ffd1224', timeout=10) 
Example 40
Project: azurectl   Author: SUSE-Enceladus   File: data_disk.py    Apache License 2.0 5 votes vote down vote up
def __generate_filename(self, identifier):
        """
            Generate vhd disk name with respect to the Azure naming
            conventions for data disks
        """
        self.data_disk_name = '%s-data-disk-%s.vhd' % (
            identifier, datetime.isoformat(datetime.utcnow()).replace(':', '_')
        )
        return self.data_disk_name 
Example 41
Project: azurectl   Author: SUSE-Enceladus   File: instance_data_disk_test.py    Apache License 2.0 5 votes vote down vote up
def setup(self):
        account = AzureAccount(
            Config(
                region_name='East US 2', filename='../data/config'
            )
        )
        self.service = mock.Mock()
        account.get_management_service = mock.Mock(return_value=self.service)
        account.get_blob_service_host_base = mock.Mock(
            return_value='test.url'
        )
        account.storage_key = mock.Mock()
        # now that that's done, instantiate a DataDisk with the account
        self.data_disk = DataDisk(account)
        # asynchronous API operations return a request object
        self.my_request = mock.Mock(request_id=Defaults.unify_id(42))
        # variables used in multiple tests
        self.cloud_service_name = 'mockcloudservice'
        self.instance_name = 'mockcloudserviceinstance1'
        self.lun = 0
        self.host_caching = 'ReadWrite'
        self.disk_filename = 'mockcloudserviceinstance1-data-disk-0.vhd'
        self.disk_name = 'mockcloudserviceinstance1-data-disk-0'
        self.disk_url = (
            'https://' +
            account.storage_name() +
            '.blob.' +
            account.get_blob_service_host_base() + '/' +
            account.storage_container() + '/' +
            self.disk_filename
        )
        self.disk_label = 'Mock data disk'
        self.disk_size = 42
        self.timestamp = datetime.utcnow()
        self.time_string = datetime.isoformat(self.timestamp).replace(':', '_')
        self.account = account 
Example 42
Project: azurectl   Author: SUSE-Enceladus   File: instance_data_disk_test.py    Apache License 2.0 5 votes vote down vote up
def test_generate_filename(self, mock_timestamp):
        mock_timestamp.utcnow = mock.Mock(return_value=self.timestamp)
        mock_timestamp.isoformat = mock.Mock(return_value=self.time_string)
        expected = '%s-data-disk-%s.vhd' % (
            self.instance_name,
            self.time_string
        )
        result = self.data_disk._DataDisk__generate_filename(
            identifier=self.instance_name
        )
        assert result == expected 
Example 43
Project: ssr-mu   Author: iv8   File: _util.py    Apache License 2.0 5 votes vote down vote up
def _now():
    """Get a timestamp for right now, formatted according to ISO 8601."""
    return datetime.isoformat(datetime.now()) 
Example 44
Project: zun   Author: kevin-zhaoshuai   File: api.py    Apache License 2.0 5 votes vote down vote up
def create_zun_service(self, values):
        values['created_at'] = datetime.isoformat(timeutils.utcnow())
        zun_service = models.ZunService(values)
        zun_service.save()
        return zun_service 
Example 45
Project: zun   Author: kevin-zhaoshuai   File: api.py    Apache License 2.0 5 votes vote down vote up
def update_zun_service(self, host, binary, values):
        try:
            target = self.client.read('/zun_services/' + host + '_' + binary)
            target_value = json.loads(target.value)
            values['updated_at'] = datetime.isoformat(timeutils.utcnow())
            target_value.update(values)
            target.value = json.dumps(target_value)
            self.client.update(target)
        except etcd.EtcdKeyNotFound:
            raise exception.ZunServiceNotFound(host=host, binary=binary)
        except Exception as e:
            LOG.error('Error occurred while updating service: %s',
                      six.text_type(e))
            raise 
Example 46
Project: serious   Author: mdrachuk   File: field_serializers.py    MIT License 5 votes vote down vote up
def dump(self, value: datetime, ctx: Dumping) -> str:
        return datetime.isoformat(value) 
Example 47
Project: serious   Author: mdrachuk   File: field_serializers.py    MIT License 5 votes vote down vote up
def dump(self, value: date, ctx: Dumping) -> str:
        return date.isoformat(value) 
Example 48
Project: serious   Author: mdrachuk   File: field_serializers.py    MIT License 5 votes vote down vote up
def dump(self, value: time, ctx: Dumping) -> str:
        return time.isoformat(value) 
Example 49
Project: token-plugin   Author: sovrin-foundation   File: test_leder_state_recovery_with_different_versions.py    Apache License 2.0 5 votes vote down vote up
def valid_upgrade(nodeSetWithIntegratedTokenPlugin, tconf):
    schedule = {}
    unow = datetime.utcnow().replace(tzinfo=dateutil.tz.tzutc())
    startAt = unow + timedelta(seconds=30000000)
    acceptableDiff = tconf.MinSepBetweenNodeUpgrades + 1
    for n in nodeSetWithIntegratedTokenPlugin[0].poolManager.nodeIds:
        schedule[n] = datetime.isoformat(startAt)
        startAt = startAt + timedelta(seconds=acceptableDiff + 3)

    return dict(name='upgrade', version="10000.10.10",
                action=START, schedule=schedule, timeout=1,
                package=None,
                sha256='db34a72a90d026dae49c3b3f0436c8d3963476c77468ad955845a1ccf7b03f55') 
Example 50
Project: token-plugin   Author: sovrin-foundation   File: test_state_recovery_with_different_versions.py    Apache License 2.0 5 votes vote down vote up
def valid_upgrade(nodeSetWithIntegratedTokenPlugin, tconf):
    schedule = {}
    unow = datetime.utcnow().replace(tzinfo=dateutil.tz.tzutc())
    startAt = unow + timedelta(seconds=30000000)
    acceptableDiff = tconf.MinSepBetweenNodeUpgrades + 1
    for n in nodeSetWithIntegratedTokenPlugin[0].poolManager.nodeIds:
        schedule[n] = datetime.isoformat(startAt)
        startAt = startAt + timedelta(seconds=acceptableDiff + 3)

    return dict(name='upgrade', version="10000.10.10",
                action=START, schedule=schedule, timeout=1,
                package=None,
                sha256='db34a72a90d026dae49c3b3f0436c8d3963476c77468ad955845a1ccf7b03f55')