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


Python pendulum.parse方法代码示例

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


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

示例1: convert_date_run

# 需要导入模块: import pendulum [as 别名]
# 或者: from pendulum import parse [as 别名]
def convert_date_run(datestring):
    """
    Convert a date of the format 'YYYY-MM-DD' to a datetime.date object.

    (Will also accept MM/DD/YYYY format, ISO 8601 timestamps, or existing
    datetime objects; these shouldn't be in COUNTER reports, but they
    do show up in real world data...)

    :param datestring: the string to convert to a date.

    :return: datetime.date object

    """
    if isinstance(datestring, datetime.date):
        return datestring

    return pendulum.parse(datestring, strict=False).date() 
开发者ID:pitthsls,项目名称:pycounter,代码行数:19,代码来源:helpers.py

示例2: getValidDateFmt

# 需要导入模块: import pendulum [as 别名]
# 或者: from pendulum import parse [as 别名]
def getValidDateFmt(irc, msg, args, state):
    date = args[0]
    valid = ['yesterday', 'tomorrow']
    check = None
    try:
        if date.lower() in valid:
            if date.lower() == 'yesterday':
                check = pendulum.yesterday().format('MM/DD/YYYY')
            else:
                check = pendulum.tomorrow().format('MM/DD/YYYY')
        else:
            check = pendulum.parse(date, strict=False).format('MM/DD/YYYY')
    except:
        pass
    if not check:
        state.errorInvalid(_('date format'), str(date))
    else:
        state.args.append(check)
        del args[0] 
开发者ID:oddluck,项目名称:limnoria-plugins,代码行数:21,代码来源:plugin.py

示例3: _getGames

# 需要导入模块: import pendulum [as 别名]
# 或者: from pendulum import parse [as 别名]
def _getGames(self, team, date, tz="US/Eastern"):
        """Given a date, populate the url with it and try to download its
        content. If successful, parse the JSON data and extract the relevant
        fields for each game. Returns a list of games."""
        url = self._getEndpointURL(date)

        # (If asking for today's results, enable the 'If-Mod.-Since' flag)
        use_cache = date == self._getTodayDate()
        # use_cache = False
        response = self._getURL(url, use_cache)
        if isinstance(response, str):
            return "ERROR: Something went wrong, check input"

        json = self._extractJSON(response)
        games = self._parseGames(json, team, tz)
        return games 
开发者ID:oddluck,项目名称:limnoria-plugins,代码行数:18,代码来源:plugin.py

示例4: _sortData

# 需要导入模块: import pendulum [as 别名]
# 或者: from pendulum import parse [as 别名]
def _sortData(self, data):
        # print(data)
        for item in data:
            # print(item)
            if item:
                if "Games with" not in item:
                    # tmp = None
                    # for game in item:
                    #    if 'Games with' in game:
                    #        tmp = item.pop()
                    item.sort(
                        key=lambda x: pendulum.parse(
                            x.split("(")[1].replace(")", ""), strict=False
                        ).int_timestamp
                    )
                # if tmp:
                #    item.append(tmp)

        return data 
开发者ID:oddluck,项目名称:limnoria-plugins,代码行数:21,代码来源:plugin.py

示例5: process_formdata

# 需要导入模块: import pendulum [as 别名]
# 或者: from pendulum import parse [as 别名]
def process_formdata(self, valuelist):
        if not valuelist:
            return
        date_str = ' '.join(valuelist)
        try:
            # Check if the datetime string is in the format without timezone, if so convert it to the
            # default timezone
            if len(date_str) == 19:
                parsed_datetime = dt.strptime(date_str, '%Y-%m-%d %H:%M:%S')
                default_timezone = self._get_default_timezone()
                self.data = default_timezone.convert(parsed_datetime)
            else:
                self.data = pendulum.parse(date_str)
        except ValueError:
            self.data = None
            raise ValueError(self.gettext('Not a valid datetime value')) 
开发者ID:apache,项目名称:airflow,代码行数:18,代码来源:forms.py

示例6: convert_type

# 需要导入模块: import pendulum [as 别名]
# 或者: from pendulum import parse [as 别名]
def convert_type(self, value, schema_type):
        """
        Takes a value from Postgres, and converts it to a value that's safe for
        JSON/Google Cloud Storage/BigQuery. Dates are converted to UTC seconds.
        Decimals are converted to floats. Times are converted to seconds.
        """
        if isinstance(value, (datetime.datetime, datetime.date)):
            return pendulum.parse(value.isoformat()).float_timestamp
        if isinstance(value, datetime.time):
            formated_time = time.strptime(str(value), "%H:%M:%S")
            return int(datetime.timedelta(
                hours=formated_time.tm_hour,
                minutes=formated_time.tm_min,
                seconds=formated_time.tm_sec).total_seconds())
        if isinstance(value, dict):
            return json.dumps(value)
        if isinstance(value, Decimal):
            return float(value)
        return value 
开发者ID:apache,项目名称:airflow,代码行数:21,代码来源:postgres_to_gcs.py

示例7: process_at_service

# 需要导入模块: import pendulum [as 别名]
# 或者: from pendulum import parse [as 别名]
def process_at_service(self, service):
        """
        当 当前时间 > at时,看[at, at + grace]之间是否有上报的数据
        """
        latest_ping = self.get_last_ping(service)
        if not latest_ping:
            return

        at = pendulum.parse(service.value, tz=settings.TIME_ZONE).in_timezone('UTC')
        last_created = pendulum.instance(latest_ping.created)
        now = pendulum.now(tz='UTC')

        if now < at.add(minutes=int(service.grace)):
            return
        if last_created < at:
            self.notify(service, now) 
开发者ID:510908220,项目名称:heartbeats,代码行数:18,代码来源:check.py

示例8: _iterate

# 需要导入模块: import pendulum [as 别名]
# 或者: from pendulum import parse [as 别名]
def _iterate(self, generator, record_preparation):
        max_bookmark = None
        for recordset in generator:
            for record in recordset:
                updated_at = pendulum.parse(record[UPDATED_TIME_KEY])

                if self.current_bookmark and self.current_bookmark >= updated_at:
                    continue
                if not max_bookmark or updated_at > max_bookmark:
                    max_bookmark = updated_at

                record = record_preparation(record)
                yield {'record': record}

            if max_bookmark:
                yield {'state': advance_bookmark(self, UPDATED_TIME_KEY, str(max_bookmark))} 
开发者ID:singer-io,项目名称:tap-facebook,代码行数:18,代码来源:__init__.py

示例9: advance_bookmark

# 需要导入模块: import pendulum [as 别名]
# 或者: from pendulum import parse [as 别名]
def advance_bookmark(stream, bookmark_key, date):
    tap_stream_id = stream.name
    state = stream.state or {}
    LOGGER.info('advance(%s, %s)', tap_stream_id, date)
    date = pendulum.parse(date) if date else None
    current_bookmark = get_start(stream, bookmark_key)

    if date is None:
        LOGGER.info('Did not get a date for stream %s '+
                    ' not advancing bookmark',
                    tap_stream_id)
    elif not current_bookmark or date > current_bookmark:
        LOGGER.info('Bookmark for stream %s is currently %s, ' +
                    'advancing to %s',
                    tap_stream_id, current_bookmark, date)
        state = singer.write_bookmark(state, tap_stream_id, bookmark_key, str(date))
    else:
        LOGGER.info('Bookmark for stream %s is currently %s ' +
                    'not changing to %s',
                    tap_stream_id, current_bookmark, date)
    return state 
开发者ID:singer-io,项目名称:tap-facebook,代码行数:23,代码来源:__init__.py

示例10: decode_literal

# 需要导入模块: import pendulum [as 别名]
# 或者: from pendulum import parse [as 别名]
def decode_literal(node, prim):
    core_type, value = next(iter(node.items()))
    if prim in ['int', 'nat']:
        return int(value)
    if prim == 'timestamp':
        if core_type == 'int':
            return pendulum.from_timestamp(int(value))
        else:
            return pendulum.parse(value)
    if prim == 'mutez':
        return Decimal(value) / 10 ** 6
    if prim == 'bool':
        return value == 'True'
    if prim == 'address' and core_type == 'bytes':
        prefix = {'0000': b'tz1', '0001': b'tz2', '0002': b'tz3'}  # TODO: check it's ttr
        return base58_encode(bytes.fromhex(value[4:]), prefix[value[:4]]).decode()
    return value 
开发者ID:murbard,项目名称:pytezos,代码行数:19,代码来源:schema.py

示例11: load_snapshots

# 需要导入模块: import pendulum [as 别名]
# 或者: from pendulum import parse [as 别名]
def load_snapshots(
    ctx: Context, label_filters: Dict[str, str]
) -> List[Snapshot]:
    snapshots = digitalocean.Manager().get_volume_snapshots()

    tag_filters = set(k+':'+v for k, v in label_filters.items())
    filtered = [snapshot
                for snapshot in snapshots
                if tag_filters.intersection(snapshot.tags)]

    _logger.debug('digitalocean.load_snaphots', label_filters=label_filters,
                  tag_filters=tag_filters, snapshots_count=len(snapshots),
                  filtered=filtered)

    return list(map(lambda snapshot: Snapshot(
        name=snapshot.id,
        created_at=pendulum.parse(snapshot.created_at),
        disk=DODiskIdentifier(volume_id=snapshot.resource_id),
    ), filtered)) 
开发者ID:miracle2k,项目名称:k8s-snapshots,代码行数:21,代码来源:digitalocean.py

示例12: test_set_state

# 需要导入模块: import pendulum [as 别名]
# 或者: from pendulum import parse [as 别名]
def test_set_state(session):
    """
    Make sure we can add a row to the DB and the content
    we expect is in the DB afterwards.
    """
    workflow_run_data = dict(
        workflow_name="DUMMY_WORKFLOW_NAME",
        parameters={"DUMMY_PARAM_NAME": "DUMMY_PARAM_VALUE"},
        state=RunState.running,
    )

    now = pendulum.parse("2016-01-02T13:00:01Z")
    with patch("pendulum.now", lambda x: now):
        WorkflowRuns.set_state(**workflow_run_data, session=session)

    rows = session.query(WorkflowRuns).all()
    assert len(rows) == 1

    row = rows[0]
    assert row.workflow_name == workflow_run_data["workflow_name"]
    assert row.parameters_hash == get_params_hash(workflow_run_data["parameters"])
    assert row.state == workflow_run_data["state"]
    assert pendulum.instance(row.timestamp) == now 
开发者ID:Flowminder,项目名称:FlowKit,代码行数:25,代码来源:test_model.py

示例13: test_set_state_with_sqlite

# 需要导入模块: import pendulum [as 别名]
# 或者: from pendulum import parse [as 别名]
def test_set_state_with_sqlite(sqlite_session):
    """
    Make sure we can add a row to a sqlite DB.
    """
    workflow_run_data = dict(
        workflow_name="DUMMY_WORKFLOW_NAME",
        parameters={"DUMMY_PARAM_NAME": "DUMMY_PARAM_VALUE"},
        state=RunState.running,
    )

    now = pendulum.parse("2016-01-02T13:00:01Z")
    with patch("pendulum.now", lambda x: now):
        WorkflowRuns.set_state(**workflow_run_data, session=sqlite_session)

    rows = sqlite_session.query(WorkflowRuns).all()
    assert len(rows) == 1

    row = rows[0]
    assert row.workflow_name == workflow_run_data["workflow_name"]
    assert row.parameters_hash == get_params_hash(workflow_run_data["parameters"])
    assert row.state == workflow_run_data["state"]
    assert pendulum.instance(row.timestamp) == now 
开发者ID:Flowminder,项目名称:FlowKit,代码行数:24,代码来源:test_model.py

示例14: parse_iso8601_duration

# 需要导入模块: import pendulum [as 别名]
# 或者: from pendulum import parse [as 别名]
def parse_iso8601_duration(cls, duration, start=None, end=None):
        match = re.match(
            r"(?:P(?P<weeks>\d+)W)|(?:P(?:(?:(?P<years>\d+)Y)?(?:(?P<months>\d+)M)?(?:(?P<days>\d+)D))?(?:T(?:(?P<hours>\d+)H)?(?:(?P<minutes>\d+)M)?(?:(?P<seconds>\d+)S)?)?)",  # noqa
            duration,
        )

        time_components = {}
        if match:
            time_components = match.groupdict(0)
            for key, value in time_components.items():
                time_components[key] = int(value)

            duration = relativedelta(**time_components)

            if start:
                return parse(start.datetime() + duration)

            if end:
                return parse(end.datetime() - duration)

        return None 
开发者ID:timofurrer,项目名称:maya,代码行数:23,代码来源:core.py

示例15: from_iso8601

# 需要导入模块: import pendulum [as 别名]
# 或者: from pendulum import parse [as 别名]
def from_iso8601(cls, s):
        # # Start and end, such as "2007-03-01T13:00:00Z/2008-05-11T15:30:00Z"
        start, end = s.split("/")
        try:
            start = parse(start)
        except pendulum.parsing.exceptions.ParserError:
            # start = self._parse_iso8601_duration(start, end=end)
            raise NotImplementedError()

        try:
            end = parse(end)
        except (pendulum.parsing.exceptions.ParserError, TypeError):
            end = cls.parse_iso8601_duration(end, start=start)

        return cls(start=start, end=end)

        # # Start and duration, such as "2007-03-01T13:00:00Z/P1Y2M10DT2H30M"
        # # Duration and end, such as "P1Y2M10DT2H30M/2008-05-11T15:30:00Z" 
开发者ID:timofurrer,项目名称:maya,代码行数:20,代码来源:core.py


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