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


Python parser.parse方法代码示例

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


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

示例1: __new__

# 需要导入模块: from dateutil import parser [as 别名]
# 或者: from dateutil.parser import parse [as 别名]
def __new__(cls, t, snap=0):
        if isinstance(t, (str, bytes)) and t.isdigit():
            t = int(t)
        if not isinstance(t, (str, bytes)):
            from dateutil.tz import tzutc
            return datetime.fromtimestamp(t // 1000, tz=tzutc())
        try:
            units = ["weeks", "days", "hours", "minutes", "seconds"]
            diffs = {u: float(t[:-1]) for u in units if u.startswith(t[-1])}
            if len(diffs) == 1:
                # Snap > 0 governs the rounding of units (hours, minutes and seconds) to 0 to improve cache performance
                snap_units = {u.rstrip("s"): 0 for u in units[units.index(list(diffs)[0]) + snap:]} if snap else {}
                snap_units.pop("day", None)
                snap_units.update(microsecond=0)
                ts = datetime.now().replace(**snap_units) + relativedelta(**diffs)
                cls._precision[ts] = snap_units
                return ts
            return dateutil_parse(t)
        except (ValueError, OverflowError, AssertionError):
            raise ValueError('Could not parse "{}" as a timestamp or time delta'.format(t)) 
开发者ID:kislyuk,项目名称:aegea,代码行数:22,代码来源:__init__.py

示例2: test_get_course_enrollments

# 需要导入模块: from dateutil import parser [as 别名]
# 或者: from dateutil.parser import parse [as 别名]
def test_get_course_enrollments(self, query_params, filter_args):
        expected_data = CourseEnrollment.objects.filter(**filter_args)
        request = APIRequestFactory().get(self.request_path + query_params)
        force_authenticate(request, user=self.staff_user)
        view = self. view_class.as_view({'get': 'list'})
        response = view(request)

        assert response.status_code == 200
        assert set(response.data.keys()) == set(
            ['count', 'next', 'previous', 'results',])

        assert len(response.data['results']) == len(expected_data)

        for data in response.data['results']:
            db_rec = expected_data.get(id=data['id'])
            assert parse(data['created']) == db_rec.created 
开发者ID:appsembler,项目名称:figures,代码行数:18,代码来源:test_course_enrollment_view.py

示例3: as_datetime

# 需要导入模块: from dateutil import parser [as 别名]
# 或者: from dateutil.parser import parse [as 别名]
def as_datetime(val):
    '''
    TODO: Add arg flag to say if caller wants end of day, beginning of day
    or a particular time of day if the param is a datetime.date obj
    '''
    if isinstance(val, datetime.datetime):
        return val
    elif isinstance(val, datetime.date):
        # Return the end of the day, set timezone to be UTC
        return datetime.datetime(
            year=val.year,
            month=val.month,
            day=val.day,
            ).replace(tzinfo=utc)

    elif isinstance(val, basestring):  # noqa: F821
        return dateutil_parse(val).replace(tzinfo=utc)
    else:
        raise TypeError(
            'value of type "{}" cannot be converted to a datetime object'.format(
                type(val))) 
开发者ID:appsembler,项目名称:figures,代码行数:23,代码来源:helpers.py

示例4: as_date

# 需要导入模块: from dateutil import parser [as 别名]
# 或者: from dateutil.parser import parse [as 别名]
def as_date(val):
    '''Casts the value to a ``datetime.date`` object if possible

    Else raises ``TypeError``
    '''
    # Important to check if datetime first because datetime.date objects
    # pass the isinstance(obj, datetime.date) test
    if isinstance(val, datetime.datetime):
        return val.date()
    elif isinstance(val, datetime.date):
        return val
    elif isinstance(val, basestring):  # noqa: F821
        return dateutil_parse(val).date()
    else:
        raise TypeError(
            'date cannot be of type "{}".'.format(type(val)) +
            ' It must be able to be cast to a datetime.date') 
开发者ID:appsembler,项目名称:figures,代码行数:19,代码来源:helpers.py

示例5: __deserialize_date

# 需要导入模块: from dateutil import parser [as 别名]
# 或者: from dateutil.parser import parse [as 别名]
def __deserialize_date(self, string):
        """Deserializes string to date.

        :param string: str.
        :return: date.
        """
        try:
            from dateutil.parser import parse
            return parse(string).date()
        except ImportError:
            return string
        except ValueError:
            raise rest.ApiException(
                status=0,
                reason="Failed to parse `{0}` as date object".format(string)
            ) 
开发者ID:alohi,项目名称:faxplus-python,代码行数:18,代码来源:api_client.py

示例6: __deserialize_datatime

# 需要导入模块: from dateutil import parser [as 别名]
# 或者: from dateutil.parser import parse [as 别名]
def __deserialize_datatime(self, string):
        """Deserializes string to datetime.

        The string should be in iso8601 datetime format.

        :param string: str.
        :return: datetime.
        """
        try:
            from dateutil.parser import parse
            return parse(string)
        except ImportError:
            return string
        except ValueError:
            raise rest.ApiException(
                status=0,
                reason=(
                    "Failed to parse `{0}` as datetime object"
                    .format(string)
                )
            ) 
开发者ID:alohi,项目名称:faxplus-python,代码行数:23,代码来源:api_client.py

示例7: detect_date

# 需要导入模块: from dateutil import parser [as 别名]
# 或者: from dateutil.parser import parse [as 别名]
def detect_date(e):
    if is_date(e): return True
    for date_type in [ datetime.datetime, datetime.date, np.datetime64 ]:
        if isinstance(e, date_type): return True

    # Slow!!!
    # for date_format in DATE_FORMATS:
    #     try:
    #         if datetime.strptime(e, date_format):
    #             return True
    #     except:
    #         continue

    # Also slow
    # try: 
    #   dparser.parse(e)
    #   return True
    # except: pass
    return False 
开发者ID:megagonlabs,项目名称:sato,代码行数:21,代码来源:type_detection.py

示例8: test_ybd

# 需要导入模块: from dateutil import parser [as 别名]
# 或者: from dateutil.parser import parse [as 别名]
def test_ybd(self):
        # If we have a 4-digit year, a non-numeric month (abbreviated or not),
        # and a day (1 or 2 digits), then there is no ambiguity as to which
        # token is a year/month/day.  This holds regardless of what order the
        # terms are in and for each of the separators below.

        seps = ['-', ' ', '/', '.']

        year_tokens = ['%Y']
        month_tokens = ['%b', '%B']
        day_tokens = ['%d']
        if PLATFORM_HAS_DASH_D:
            day_tokens.append('%-d')

        prods = itertools.product(year_tokens, month_tokens, day_tokens)
        perms = [y for x in prods for y in itertools.permutations(x)]
        unambig_fmts = [sep.join(perm) for sep in seps for perm in perms]

        actual = datetime(2003, 9, 25)

        for fmt in unambig_fmts:
            dstr = actual.strftime(fmt)
            res = parse(dstr)
            self.assertEqual(res, actual) 
开发者ID:MediaBrowser,项目名称:plugin.video.emby,代码行数:26,代码来源:test_parser.py

示例9: testParseUnicodeWords

# 需要导入模块: from dateutil import parser [as 别名]
# 或者: from dateutil.parser import parse [as 别名]
def testParseUnicodeWords(self):

        class rus_parserinfo(parserinfo):
            MONTHS = [("янв", "Январь"),
                      ("фев", "Февраль"),
                      ("мар", "Март"),
                      ("апр", "Апрель"),
                      ("май", "Май"),
                      ("июн", "Июнь"),
                      ("июл", "Июль"),
                      ("авг", "Август"),
                      ("сен", "Сентябрь"),
                      ("окт", "Октябрь"),
                      ("ноя", "Ноябрь"),
                      ("дек", "Декабрь")]

        self.assertEqual(parse('10 Сентябрь 2015 10:20',
                               parserinfo=rus_parserinfo()),
                         datetime(2015, 9, 10, 10, 20)) 
开发者ID:MediaBrowser,项目名称:plugin.video.emby,代码行数:21,代码来源:test_parser.py

示例10: countdown

# 需要导入模块: from dateutil import parser [as 别名]
# 或者: from dateutil.parser import parse [as 别名]
def countdown(self, countdown_target_str: str, stage_name: str, ctx: Context):
        countdown_target = parse(countdown_target_str).date()

        # Get the current date
        today = datetime.date.today()
        time_until_target = relativedelta(countdown_target, today)

        # Given a number of items, determine whether it should be pluralised.
        # Then, return the suffix of 's' if it should be, and '' if it shouldn't.
        def suffix_from_number(num):
            return "" if num == 1 else "s"

        month_or_months = "month" + suffix_from_number(time_until_target.months)
        day_or_days = "day" + suffix_from_number(time_until_target.days)

        month_countdown = f"{time_until_target.months} {month_or_months}"
        day_countdown = f"{time_until_target.days} {day_or_days}"

        # Diable the months component of the countdown when there are no months left
        if time_until_target.months:
            month_and_day_countdown = f"{month_countdown} and {day_countdown}"
        else:
            month_and_day_countdown = day_countdown

        if today > countdown_target:
            await ctx.send(f"{stage_name} has begun!")
            return
        await ctx.send(
            f"{stage_name} begins on the {countdown_target_str}.\n"
            f"That's in {month_and_day_countdown}!"
        ) 
开发者ID:CyberDiscovery,项目名称:cyberdisc-bot,代码行数:33,代码来源:cyber.py

示例11: string_date_time

# 需要导入模块: from dateutil import parser [as 别名]
# 或者: from dateutil.parser import parse [as 别名]
def string_date_time(dstr):
    d = parser.parse(dstr).astimezone(tz)
    return d.strftime("%Y-%m-%d"), d.strftime("%H:%M:%S") 
开发者ID:tuna,项目名称:fishroom,代码行数:5,代码来源:helpers.py

示例12: setup

# 需要导入模块: from dateutil import parser [as 别名]
# 或者: from dateutil.parser import parse [as 别名]
def setup(self, db):
        super(TestSiteDailyMetricsView, self).setup(db)
        self.first_day = parse('2018-01-01')
        self.last_day = parse('2018-03-31')
        self.date_fields = set(['date_for', 'created', 'modified',])
        self.expected_results_keys = set([o.name for o in SiteDailyMetrics._meta.fields])
        field_names = (o.name for o in SiteDailyMetrics._meta.fields
            if o.name not in self.date_fields )

        self.metrics = generate_sdm_series(self.site, self.first_day, self.last_day) 
开发者ID:appsembler,项目名称:figures,代码行数:12,代码来源:test_site_daily_metrics_view.py

示例13: test_get_by_date_range

# 需要导入模块: from dateutil import parser [as 别名]
# 或者: from dateutil.parser import parse [as 别名]
def test_get_by_date_range(self, first_day, last_day):
        '''
        Note: This test is sensitive in the order data are compared. It expects
        that records are retrieved by date_for, descending.

        TODO: Add more date ranges
        '''
        endpoint = '{}?date_0={}&date_1={}'.format(
            self.request_path, first_day, last_day)

        expected_data = SiteDailyMetrics.objects.filter(
            date_for__range=(first_day, last_day))
        factory = APIRequestFactory()
        request = factory.get(endpoint)
        force_authenticate(request, user=self.staff_user)
        view = self.view_class.as_view({'get':'list'})
        response = view(request)
        assert response.status_code == 200
        # Expect the following format for pagination
        # {
        #     "count": 2,
        #     "next": null, # or a url
        #     "previous": null, # or a url
        #     "results": [
        #     ...           # list of the results
        #     ]
        # }
        assert set(response.data.keys()) == set(
            ['count', 'next', 'previous', 'results',])
        assert len(response.data['results']) == FiguresLimitOffsetPagination.default_limit

        # Hack: Check date and datetime values explicitly
        for data in response.data['results']:
            db_rec = expected_data.get(id=data['id'])
            assert data['date_for'] == str(db_rec.date_for)
            assert parse(data['created']) == db_rec.created
            assert parse(data['modified']) == db_rec.modified
        check_fields = self.expected_results_keys - self.date_fields - set(['site'])
        for field_name in check_fields:
            assert data[field_name] == getattr(db_rec,field_name) 
开发者ID:appsembler,项目名称:figures,代码行数:42,代码来源:test_site_daily_metrics_view.py

示例14: setup

# 需要导入模块: from dateutil import parser [as 别名]
# 或者: from dateutil.parser import parse [as 别名]
def setup(self, db):

        super(TestCourseDailyMetricsView, self).setup(db)
        self.first_day = parse('2018-01-01')
        self.last_day = parse('2018-03-31')
        self.date_fields = set(['date_for', 'created', 'modified',])
        self.expected_results_keys = set([o.name for o in CourseDailyMetrics._meta.fields])
        field_names = (o.name for o in CourseDailyMetrics._meta.fields
            if o.name not in self.date_fields )

        self.metrics = generate_cdm_series(self.site, self.first_day, self.last_day) 
开发者ID:appsembler,项目名称:figures,代码行数:13,代码来源:test_course_daily_metrics_view.py

示例15: assert_response_equal

# 需要导入模块: from dateutil import parser [as 别名]
# 或者: from dateutil.parser import parse [as 别名]
def assert_response_equal(self, response_data, obj):
        '''Convenience method to compare serialized data to model object
        '''
        # Hack: Check date and datetime values explicitly
        assert response_data['date_for'] == str(obj.date_for)
        assert parse(response_data['created']) == obj.created
        assert parse(response_data['modified']) == obj.modified
        check_fields = self.expected_results_keys - self.date_fields - set(['site'])
        for field_name in check_fields:
            obj_field = getattr(obj, field_name)
            if (type(response_data) in (float, Decimal,) or 
                type(obj_field) in (float, Decimal,)):
                assert float(response_data[field_name]) == pytest.approx(obj_field)
            else:
                assert response_data[field_name] == obj_field 
开发者ID:appsembler,项目名称:figures,代码行数:17,代码来源:test_course_daily_metrics_view.py


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