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


Python datetime.fromisoformat方法代码示例

本文整理汇总了Python中datetime.datetime.fromisoformat方法的典型用法代码示例。如果您正苦于以下问题:Python datetime.fromisoformat方法的具体用法?Python datetime.fromisoformat怎么用?Python datetime.fromisoformat使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在datetime.datetime的用法示例。


在下文中一共展示了datetime.fromisoformat方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: update_or_add_item

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromisoformat [as 别名]
def update_or_add_item(repo_items, commit_hash, item, definition, commit_timestamps,
                       equal_fn, type_ctor):
    # If we've seen this item before, check previous definitions
    if item in repo_items:
        prev_defns = repo_items[item][HISTORY_KEY]
        max_defn_i = max(range(len(prev_defns)),
                         key=lambda i: datetime.fromisoformat(prev_defns[i][DATES_KEY]["last"]))
        max_defn = prev_defns[max_defn_i]

        # If equal to previous commit, update date and commit on existing definition
        if equal_fn(definition, max_defn):
            new_defn = make_item_defn(max_defn, commit_hash, commit_timestamps)
            repo_items[item][HISTORY_KEY][max_defn_i] = new_defn

        # Otherwise, prepend changed definition for existing item
        else:
            new_defn = make_item_defn(definition, commit_hash, commit_timestamps)
            repo_items[item][HISTORY_KEY] = prev_defns + [new_defn]

    # We haven't seen this item before, add it
    else:
        defn = make_item_defn(definition, commit_hash, commit_timestamps)
        repo_items[item] = type_ctor(defn, item)

    return repo_items 
开发者ID:mozilla,项目名称:probe-scraper,代码行数:27,代码来源:transform_probes.py

示例2: datetime_parser

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromisoformat [as 别名]
def datetime_parser(data: dict) -> dict:
    """
    Convert ISO strings into datetime objects
    """
    for key, val in data.items():
        if isinstance(val, str):
            if "+00:00" in val:
                try:
                    data[key] = datetime.fromisoformat(val)
                except ValueError:
                    pass
            try:
                data[key] = datetime.strptime(val, r"%Y-%m-%d")
            except ValueError:
                pass
    return data 
开发者ID:avwx-rest,项目名称:avwx-engine,代码行数:18,代码来源:util.py

示例3: criar_no_pagseguro

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromisoformat [as 别名]
def criar_no_pagseguro(self) -> 'PlanoAutomaticoRecorrente':
        """
        Cria um plano automático na conta do pagseguro
        :return: código do plano criado
        """
        headers = {
            'Content-Type': 'application/json;charset=UTF-8',
            'Accept': 'application/vnd.pagseguro.com.br.v3+json;charset=ISO-8859-1'
        }
        response = requests.post(self._config.construir_url('/pre-approvals/request'), json=self._main_data,
                                 headers=headers)
        codigo_data = response.json()
        if codigo_data.get('error', False):
            raise PagseguroException(codigo_data, response.status_code)
        dt = datetime.fromisoformat(codigo_data['date']).astimezone(pytz.UTC)
        return PlanoAutomaticoRecorrente(codigo_data['code'], dt) 
开发者ID:renzon,项目名称:pygseguro,代码行数:18,代码来源:plano_recorrente_automatico.py

示例4: test_dataframe_datetime_column

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromisoformat [as 别名]
def test_dataframe_datetime_column(self):
        assert_arrow_table_equals(
            dataframe_to_arrow_table(
                pd.DataFrame(
                    {"A": ["2019-09-17T21:21:00.123456Z", None]}, dtype="datetime64[ns]"
                ),
                [Column("A", ColumnType.DATETIME())],
                self.path,
            ),
            arrow_table(
                {
                    "A": pyarrow.array(
                        [dt.fromisoformat("2019-09-17T21:21:00.123456"), None],
                        type=pyarrow.timestamp(unit="ns", tz=None),
                    )
                },
                [atypes.Column("A", atypes.ColumnType.Datetime())],
            ),
        ) 
开发者ID:CJWorkbench,项目名称:cjworkbench,代码行数:21,代码来源:test_types.py

示例5: test_arrow_datetime_column

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromisoformat [as 别名]
def test_arrow_datetime_column(self):
        dataframe, columns = arrow_table_to_dataframe(
            arrow_table(
                {
                    "A": pyarrow.array(
                        [dt.fromisoformat("2019-09-17T21:21:00.123456"), None],
                        type=pyarrow.timestamp(unit="ns", tz=None),
                    )
                },
                [atypes.Column("A", atypes.ColumnType.Datetime())],
            )
        )
        assert_frame_equal(
            dataframe,
            pd.DataFrame(
                {"A": ["2019-09-17T21:21:00.123456Z", None]}, dtype="datetime64[ns]"
            ),
        )
        self.assertEqual(columns, [Column("A", ColumnType.DATETIME())]) 
开发者ID:CJWorkbench,项目名称:cjworkbench,代码行数:21,代码来源:test_types.py

示例6: fetch_data

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromisoformat [as 别名]
def fetch_data(category, type):
    try:
        response = requests.get('https://api.fitbit.com/1/user/-/' + category + '/' + type + '/date/today/1d.json', 
            headers={'Authorization': 'Bearer ' + FITBIT_ACCESS_TOKEN, 'Accept-Language': FITBIT_LANGUAGE})
        response.raise_for_status()
    except requests.exceptions.HTTPError as err:
        print("HTTP request failed: %s" % (err))
        sys.exit()

    data = response.json()
    print("Got " + type + " from Fitbit")

    for day in data[category.replace('/', '-') + '-' + type]:
        points.append({
                "measurement": type,
                "time": LOCAL_TIMEZONE.localize(datetime.fromisoformat(day['dateTime'])).astimezone(pytz.utc).isoformat(),
                "fields": {
                    "value": float(day['value'])
                }
            }) 
开发者ID:c99koder,项目名称:personal-influxdb,代码行数:22,代码来源:fitbit.py

示例7: process_levels

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromisoformat [as 别名]
def process_levels(levels):
    for level in levels:
        type = level['level']
        if type == "asleep":
            type = "light"
        if type == "restless":
            type = "rem"
        if type == "awake":
            type = "wake"

        time = datetime.fromisoformat(level['dateTime'])
        utc_time = LOCAL_TIMEZONE.localize(time).astimezone(pytz.utc).isoformat()
        points.append({
                "measurement": "sleep_levels",
                "time": utc_time,
                "fields": {
                    "seconds": int(level['seconds'])
                }
            }) 
开发者ID:c99koder,项目名称:personal-influxdb,代码行数:21,代码来源:fitbit.py

示例8: inspect_running_containers

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromisoformat [as 别名]
def inspect_running_containers() -> datetime:
    log.info("Inspecting running containers.")
    last_event_time = datetime.utcnow()
    containers = cfg.client.containers.list(ignore_removed=True, sparse=True)

    for container in containers:
        container_id = container.id
        data = cfg.client.api.inspect_container(container_id)
        last_event_time = max(
            last_event_time,
            # not sure why mypy doesn't know about this method:
            datetime.fromisoformat(data['State']['StartedAt'][:26]),  # type: ignore
        )
        process_started_container_labels(
            container_id, paused=container.status == 'paused'
        )

    log.debug('Finished inspection of running containers.')
    return last_event_time 
开发者ID:funkyfuture,项目名称:deck-chores,代码行数:21,代码来源:main.py

示例9: parse_date

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromisoformat [as 别名]
def parse_date(str_date):
    try:
        return datetime.fromisoformat(str_date)
    except Exception:
        formats = ('%Y-%m-%dT%H:%M:%S.%f%z',
                   '%Y-%m-%dT%H:%M:%S.%f',
                   '%Y-%m-%dT%H:%M:%S',
                   '%Y-%m-%dT%H:%M',
                   '%Y-%m-%d %H:%M:%S.%f%z',
                   '%Y-%m-%d %H:%M:%S.%f',
                   '%Y-%m-%d %H:%M:%S',
                   '%Y-%m-%d %H:%M',
                   '%Y-%m-%d',)
        for format in formats:
            with ignored(ValueError):
                return datetime.strptime(str_date, format)
        raise ValueError('Date format is unknown') 
开发者ID:pyecore,项目名称:pyecore,代码行数:19,代码来源:innerutils.py

示例10: _parse_datetime

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromisoformat [as 别名]
def _parse_datetime(value: str) -> datetime:
    try:
        return datetime.fromisoformat(value)
    except ValueError:
        return parse_date(value) 
开发者ID:pgjones,项目名称:quart,代码行数:7,代码来源:tag.py

示例11: fromisoformat

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromisoformat [as 别名]
def fromisoformat(iso):
    """ for python versions < 3.7 get datetime from isoformat """
    d, t = iso.split('T')
    year, month, day = d.split('-')
    hours, minutes, seconds = t.split(':')
    seconds = float(seconds[0:-1])
    sec = int(seconds)
    microseconds = int((seconds-sec)*1e6)

    return datetime(int(year), int(month), int(day), int(hours), int(minutes), sec, microseconds) 
开发者ID:fitoprincipe,项目名称:ipygee,代码行数:12,代码来源:tasks.py

示例12: _create_tuple_datetime

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromisoformat [as 别名]
def _create_tuple_datetime(name, time):
        nt = namedtuple(name, ('utc', 'local', 'str'))
        if not time:
            return nt(utc=None, local=None, str='')

        try:
            utc = datetime.fromisoformat(time)
        except AttributeError:
            utc = fromisoformat(time)

        utc = utc.replace(tzinfo=tz.tzutc())
        local = utc.astimezone(tz.tzlocal())
        string = local.isoformat()
        return nt(utc=utc, local=local, str=string) 
开发者ID:fitoprincipe,项目名称:ipygee,代码行数:16,代码来源:tasks.py

示例13: _defcon_action

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromisoformat [as 别名]
def _defcon_action(self, ctx: Context, days: int, action: Action) -> None:
        """Providing a structured way to do an defcon action."""
        try:
            response = await self.bot.api_client.get('bot/bot-settings/defcon')
            data = response['data']

            if "enable_date" in data and action is Action.DISABLED:
                enabled = datetime.fromisoformat(data["enable_date"])

                delta = datetime.now() - enabled

                self.bot.stats.timing("defcon.enabled", delta)
        except Exception:
            pass

        error = None
        try:
            await self.bot.api_client.put(
                'bot/bot-settings/defcon',
                json={
                    'name': 'defcon',
                    'data': {
                        # TODO: retrieve old days count
                        'days': days,
                        'enabled': action is not Action.DISABLED,
                        'enable_date': datetime.now().isoformat()
                    }
                }
            )
        except Exception as err:
            log.exception("Unable to update DEFCON settings.")
            error = err
        finally:
            await ctx.send(self.build_defcon_msg(action, error))
            await self.send_defcon_log(action, ctx.author, error)

            self.bot.stats.gauge("defcon.threshold", days) 
开发者ID:python-discord,项目名称:bot,代码行数:39,代码来源:defcon.py

示例14: retrieve_files

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromisoformat [as 别名]
def retrieve_files(repo_info, cache_dir):
    results = defaultdict(list)
    timestamps = dict()
    base_path = os.path.join(cache_dir, repo_info.name)

    min_date = None
    if repo_info.name in MIN_DATES:
        min_date = utc_timestamp(datetime.fromisoformat(MIN_DATES[repo_info.name]))

    if os.path.exists(repo_info.name):
        shutil.rmtree(repo_info.name)
    repo = Repo.clone_from(repo_info.url, repo_info.name)
    repo.git.checkout(repo_info.branch)

    try:
        for rel_path in repo_info.get_change_files():
            hashes = get_commits(repo, rel_path)
            for _hash, (ts, index) in hashes.items():
                if (min_date and ts < min_date):
                    continue

                disk_path = os.path.join(base_path, _hash, rel_path)
                if not os.path.exists(disk_path):
                    contents = get_file_at_hash(repo, _hash, rel_path)

                    dir = os.path.split(disk_path)[0]
                    if not os.path.exists(dir):
                        os.makedirs(dir)
                    with open(disk_path, 'wb') as f:
                        f.write(contents.encode("UTF-8"))

                results[_hash].append(disk_path)
                timestamps[_hash] = (ts, index)
    except Exception:
        # without this, the error will be silently discarded
        raise
    finally:
        shutil.rmtree(repo_info.name)

    return timestamps, results 
开发者ID:mozilla,项目名称:probe-scraper,代码行数:42,代码来源:git_scraper.py

示例15: __init__

# 需要导入模块: from datetime import datetime [as 别名]
# 或者: from datetime.datetime import fromisoformat [as 别名]
def __init__(self):
        """Initializer."""
        if Config.MASU_DATE_OVERRIDE and Config.DEBUG and DateAccessor.mock_date_time is None:
            # python-dateutil is needed in Python <=3.6.x;
            # in Python 3.7 there is datetime.fromisoformat()
            DateAccessor.mock_date_time = parser.parse(Config.MASU_DATE_OVERRIDE)
            if DateAccessor.mock_date_time.tzinfo is None:
                DateAccessor.mock_date_time = DateAccessor.mock_date_time.replace(tzinfo=pytz.UTC)
            LOG.info("Initializing masu date/time to %s", str(DateAccessor.mock_date_time)) 
开发者ID:project-koku,项目名称:koku,代码行数:11,代码来源:date_accessor.py


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