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


Python DateDataParser.get_date_data方法代码示例

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


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

示例1: __call__

# 需要导入模块: from dateparser.date import DateDataParser [as 别名]
# 或者: from dateparser.date.DateDataParser import get_date_data [as 别名]
	def __call__(self,values):
		ddp = DateDataParser()
		values = ''.join(values)
		values = values.replace(u'\u00ab',"")
		values = values.replace(u'\u00bb',"")
		dateobj = ddp.get_date_data(values)['date_obj']
		return dateobj.strftime("%B %d, %Y, %H:%M:%S")
开发者ID:GorioB,项目名称:pmscanner,代码行数:9,代码来源:processors.py

示例2: TestDateParser

# 需要导入模块: from dateparser.date import DateDataParser [as 别名]
# 或者: from dateparser.date.DateDataParser import get_date_data [as 别名]

#.........这里部分代码省略.........
        # Japanese dates
        param('2016年3月20日(日) 21時40分', datetime(2016, 3, 20, 21, 40)),
        param("2016年3月20日 21時40分", datetime(2016, 3, 20, 21, 40)),
        # Numeric dates
        param('06-17-2014', datetime(2014, 6, 17)),
        param('13/03/2014', datetime(2014, 3, 13)),
        param('11. 12. 2014, 08:45:39', datetime(2014, 11, 12, 8, 45, 39)),
        # Miscellaneous dates
        param('1 Ni 2015', datetime(2015, 4, 1, 0, 0)),
        param('1 Mar 2015', datetime(2015, 3, 1, 0, 0)),
        param('1 Paz 2015', datetime(2015, 10, 1, 0, 0)),
        param('1 сер 2015', datetime(2015, 8, 1, 0, 0)),
        param('2016020417:10', datetime(2016, 2, 4, 17, 10)),
        # Chinese dates
        param('2015年04月08日10:05', datetime(2015, 4, 8, 10, 5)),
        param('2012年12月20日10:35', datetime(2012, 12, 20, 10, 35)),
        param('2016年06月30日09时30分', datetime(2016, 6, 30, 9, 30)),
        param('2016年6月2911:30', datetime(2016, 6, 29, 11, 30)),
        param('2016年6月29', datetime(2016, 6, 29, 0, 0)),
        param('2016年 2月 5日', datetime(2016, 2, 5, 0, 0)),
    ])
    def test_dates_parsing(self, date_string, expected):
        self.given_local_tz_offset(0)
        self.given_parser(settings={'NORMALIZE': False,
                                    'RELATIVE_BASE': datetime(2012, 11, 13)})
        self.when_date_is_parsed(date_string)
        self.then_date_was_parsed_by_date_parser()
        self.then_period_is('day')
        self.then_date_obj_exactly_is(expected)

    def test_stringified_datetime_should_parse_fine(self):
        expected_date = datetime(2012, 11, 13, 10, 15, 5, 330256)
        self.given_parser(settings={'RELATIVE_BASE': expected_date})
        date_string = str(self.parser.get_date_data('today')['date_obj'])
        self.when_date_is_parsed(date_string)
        self.then_date_was_parsed_by_date_parser()
        self.then_period_is('day')
        self.then_date_obj_exactly_is(expected_date)

    @parameterized.expand([
        # English dates
        param('[Sept] 04, 2014.', datetime(2014, 9, 4)),
        param('Tuesday Jul 22, 2014', datetime(2014, 7, 22)),
        param('10:04am EDT', datetime(2012, 11, 13, 14, 4)),
        param('Friday', datetime(2012, 11, 9)),
        param('November 19, 2014 at noon', datetime(2014, 11, 19, 12, 0)),
        param('December 13, 2014 at midnight', datetime(2014, 12, 13, 0, 0)),
        param('Nov 25 2014 10:17 pm EST', datetime(2014, 11, 26, 3, 17)),
        param('Wed Aug 05 12:00:00 EDT 2015', datetime(2015, 8, 5, 16, 0)),
        param('April 9, 2013 at 6:11 a.m.', datetime(2013, 4, 9, 6, 11)),
        param('Aug. 9, 2012 at 2:57 p.m.', datetime(2012, 8, 9, 14, 57)),
        param('December 10, 2014, 11:02:21 pm', datetime(2014, 12, 10, 23, 2, 21)),
        param('8:25 a.m. Dec. 12, 2014', datetime(2014, 12, 12, 8, 25)),
        param('2:21 p.m., December 11, 2014', datetime(2014, 12, 11, 14, 21)),
        param('Fri, 12 Dec 2014 10:55:50', datetime(2014, 12, 12, 10, 55, 50)),
        param('20 Mar 2013 10h11', datetime(2013, 3, 20, 10, 11)),
        param('10:06am Dec 11, 2014', datetime(2014, 12, 11, 10, 6)),
        param('19 February 2013 year 09:10', datetime(2013, 2, 19, 9, 10)),
        # French dates
        param('11 Mai 2014', datetime(2014, 5, 11)),
        param('dimanche, 11 Mai 2014', datetime(2014, 5, 11)),
        param('22 janvier 2015 à 14h40', datetime(2015, 1, 22, 14, 40)), #wrong
        param('Dimanche 1er Février à 21:24', datetime(2012, 2, 1, 21, 24)),
        param('vendredi, décembre 5 2014.', datetime(2014, 12, 5, 0, 0)),
        param('le 08 Déc 2014 15:11', datetime(2014, 12, 8, 15, 11)),
        param('Le 11 Décembre 2014 à 09:00', datetime(2014, 12, 11, 9, 0)),
开发者ID:brechmos,项目名称:dateparser,代码行数:70,代码来源:test_date_parser.py

示例3: _parse_date

# 需要导入模块: from dateparser.date import DateDataParser [as 别名]
# 或者: from dateparser.date.DateDataParser import get_date_data [as 别名]
 def _parse_date(self, string):
     parser = DateDataParser()
     date = parser.get_date_data(string)['date_obj']
     if date is None:
         raise RuntimeError('Unable to parse date: {!r}'.format(string))
     return date.date()
开发者ID:pombredanne,项目名称:pynab,代码行数:8,代码来源:models.py

示例4: TestDateParser

# 需要导入模块: from dateparser.date import DateDataParser [as 别名]
# 或者: from dateparser.date.DateDataParser import get_date_data [as 别名]

#.........这里部分代码省略.........
        self.given_configuration('PREFER_DAY_OF_MONTH', prefer_day_of_month)
        self.given_utcnow(datetime(2015, 2, 12))
        self.given_parser()
        self.when_date_is_parsed('24 April 2012')
        self.then_date_was_parsed_by_date_parser()
        self.then_date_obj_exactly_is(datetime(2012, 4, 24))

    @parameterized.expand([
        param('29 February 2015'),
        param('32 January 2015'),
        param('31 April 2015'),
        param('31 June 2015'),
        param('31 September 2015'),
    ])
    def test_error_should_be_raised_for_invalid_dates_with_too_large_day_number(self, date_string):
        self.when_date_is_parsed_by_date_parser(date_string)
        self.then_error_was_raised(ValueError, ['Day not in range for month'])

    @parameterized.expand([
        param('2015-05-02T10:20:19+0000', languages=['fr'], expected=datetime(2015, 5, 2, 10, 20, 19)),
        param('2015-05-02T10:20:19+0000', languages=['en'], expected=datetime(2015, 5, 2, 10, 20, 19)),
        param('2015-05-02T10:20:19+0000', languages=[], expected=datetime(2015, 5, 2, 10, 20, 19)),
    ])
    def test_iso_datestamp_format_should_always_parse(self, date_string, languages, expected):
        self.given_local_tz_offset(0)
        self.given_parser(languages=languages)
        self.when_date_is_parsed(date_string)
        self.then_date_was_parsed_by_date_parser()
        self.then_date_obj_exactly_is(expected)

    @parameterized.expand([
        param('10 December', expected=datetime(2015, 12, 10), period='day'),
        param('March', expected=datetime(2015, 3, 15), period='month'),
        param('April', expected=datetime(2015, 4, 15), period='month'),
        param('December', expected=datetime(2015, 12, 15), period='month'),
        param('Friday', expected=datetime(2015, 2, 13), period='day'),
        param('Monday', expected=datetime(2015, 2, 9), period='day'),
        param('10:00PM', expected=datetime(2015, 2, 15, 22, 00), period='day'),
        param('16:10', expected=datetime(2015, 2, 15, 16, 10), period='day'),
        param('2014', expected=datetime(2014, 2, 15), period='year'),
        param('2008', expected=datetime(2008, 2, 15), period='year'),
    ])
    def test_extracted_period(self, date_string, expected=None, period=None):
        self.given_utcnow(datetime(2015, 2, 15, 15, 30))  # Sunday
        self.given_local_tz_offset(0)
        self.given_parser()
        self.when_date_is_parsed(date_string)
        self.then_date_was_parsed_by_date_parser()
        self.then_date_obj_exactly_is(expected)
        self.then_period_is(period)

    def given_utcnow(self, now):
        datetime_mock = Mock(wraps=datetime)
        datetime_mock.utcnow = Mock(return_value=now)
        self.add_patch(patch('dateparser.date_parser.datetime', new=datetime_mock))

    def given_local_tz_offset(self, offset):
        self.add_patch(
            patch.object(dateparser.timezone_parser,
                         'local_tz_offset',
                         new=timedelta(seconds=3600 * offset))
        )

    def given_parser(self, *args, **kwds):
        def collecting_get_date_data(parse):
            @wraps(parse)
            def wrapped(date_string):
                self.date_result = parse(date_string)
                return self.date_result
            return wrapped

        self.add_patch(patch.object(date_parser,
                                    'parse',
                                    collecting_get_date_data(date_parser.parse)))

        self.date_parser = Mock(wraps=date_parser)
        self.add_patch(patch('dateparser.date.date_parser', new=self.date_parser))
        self.parser = DateDataParser(*args, **kwds)

    def given_configuration(self, key, value):
        self.add_patch(patch.object(settings, key, new=value))

    def when_date_is_parsed(self, date_string):
        self.result = self.parser.get_date_data(date_string)

    def when_date_is_parsed_by_date_parser(self, date_string):
        try:
            self.result = DateParser().parse(date_string)
        except Exception as error:
            self.error = error

    def then_period_is(self, period):
        self.assertEqual(period, self.result['period'])

    def then_date_obj_exactly_is(self, expected):
        self.assertEqual(expected, self.result['date_obj'])

    def then_date_was_parsed_by_date_parser(self):
        self.assertNotEqual(NotImplemented, self.date_result, "Date was not parsed")
        self.assertEqual(self.result['date_obj'], self.date_result[0])
开发者ID:Type-of-Python,项目名称:dateparser,代码行数:104,代码来源:test_date_parser.py

示例5: TestDateParser

# 需要导入模块: from dateparser.date import DateDataParser [as 别名]
# 或者: from dateparser.date.DateDataParser import get_date_data [as 别名]

#.........这里部分代码省略.........
            param("1978, 1 Peb, 7:05 PM", datetime(1978, 2, 1, 19, 5)),
            param("2 hun", datetime(2012, 6, 2)),
            param("Lin 16:16", datetime(2012, 11, 11, 16, 16)),
            # Japanese dates
            param("2016年3月20日(日) 21時40分", datetime(2016, 3, 20, 21, 40)),
            param("2016年3月20日 21時40分", datetime(2016, 3, 20, 21, 40)),
            # Numeric dates
            param("06-17-2014", datetime(2014, 6, 17)),
            param("13/03/2014", datetime(2014, 3, 13)),
            param("11. 12. 2014, 08:45:39", datetime(2014, 11, 12, 8, 45, 39)),
            # Miscellaneous dates
            param("1 Ni 2015", datetime(2015, 4, 1, 0, 0)),
            param("1 Mar 2015", datetime(2015, 3, 1, 0, 0)),
            param("1 Paz 2015", datetime(2015, 10, 1, 0, 0)),
            param("1 сер 2015", datetime(2015, 8, 1, 0, 0)),
            param("2016020417:10", datetime(2016, 2, 4, 17, 10)),
            # Chinese dates
            param("2015年04月08日10:05", datetime(2015, 4, 8, 10, 5)),
            param("2012年12月20日10:35", datetime(2012, 12, 20, 10, 35)),
            param("2016年 2月 5日", datetime(2016, 2, 5, 0, 0)),
        ]
    )
    def test_dates_parsing(self, date_string, expected):
        self.given_local_tz_offset(0)
        self.given_parser(settings={"NORMALIZE": False, "RELATIVE_BASE": datetime(2012, 11, 13)})
        self.when_date_is_parsed(date_string)
        self.then_date_was_parsed_by_date_parser()
        self.then_period_is("day")
        self.then_date_obj_exactly_is(expected)

    def test_stringified_datetime_should_parse_fine(self):
        expected_date = datetime(2012, 11, 13, 10, 15, 5, 330256)
        self.given_parser(settings={"RELATIVE_BASE": expected_date})
        date_string = str(self.parser.get_date_data("today")["date_obj"])
        self.when_date_is_parsed(date_string)
        self.then_date_was_parsed_by_date_parser()
        self.then_period_is("day")
        self.then_date_obj_exactly_is(expected_date)

    @parameterized.expand(
        [
            # English dates
            param("[Sept] 04, 2014.", datetime(2014, 9, 4)),
            param("Tuesday Jul 22, 2014", datetime(2014, 7, 22)),
            param("10:04am EDT", datetime(2012, 11, 13, 14, 4)),
            param("Friday", datetime(2012, 11, 9)),
            param("November 19, 2014 at noon", datetime(2014, 11, 19, 12, 0)),
            param("December 13, 2014 at midnight", datetime(2014, 12, 13, 0, 0)),
            param("Nov 25 2014 10:17 pm EST", datetime(2014, 11, 26, 3, 17)),
            param("Wed Aug 05 12:00:00 EDT 2015", datetime(2015, 8, 5, 16, 0)),
            param("April 9, 2013 at 6:11 a.m.", datetime(2013, 4, 9, 6, 11)),
            param("Aug. 9, 2012 at 2:57 p.m.", datetime(2012, 8, 9, 14, 57)),
            param("December 10, 2014, 11:02:21 pm", datetime(2014, 12, 10, 23, 2, 21)),
            param("8:25 a.m. Dec. 12, 2014", datetime(2014, 12, 12, 8, 25)),
            param("2:21 p.m., December 11, 2014", datetime(2014, 12, 11, 14, 21)),
            param("Fri, 12 Dec 2014 10:55:50", datetime(2014, 12, 12, 10, 55, 50)),
            param("20 Mar 2013 10h11", datetime(2013, 3, 20, 10, 11)),
            param("10:06am Dec 11, 2014", datetime(2014, 12, 11, 10, 6)),
            param("19 February 2013 year 09:10", datetime(2013, 2, 19, 9, 10)),
            # French dates
            param("11 Mai 2014", datetime(2014, 5, 11)),
            param("dimanche, 11 Mai 2014", datetime(2014, 5, 11)),
            param("22 janvier 2015 à 14h40", datetime(2015, 1, 22, 14, 40)),  # wrong
            param("Dimanche 1er Février à 21:24", datetime(2012, 2, 1, 21, 24)),
            param("vendredi, décembre 5 2014.", datetime(2014, 12, 5, 0, 0)),
            param("le 08 Déc 2014 15:11", datetime(2014, 12, 8, 15, 11)),
开发者ID:youngilcho,项目名称:dateparser,代码行数:70,代码来源:test_date_parser.py

示例6: TestFreshnessDateDataParser

# 需要导入模块: from dateparser.date import DateDataParser [as 别名]
# 或者: from dateparser.date.DateDataParser import get_date_data [as 别名]

#.........这里部分代码省略.........
        param('5000 years ago'),
        param('2014 years ago'),  # We've fixed .now in setUp
        param('{} months ago'.format(2013 * 12 + 9)),
    ])
    def test_dates_not_supported_by_date_time(self, date_string):
        self.given_parser()
        self.given_date_string(date_string)
        self.when_date_is_parsed()
        self.then_error_was_raised(ValueError, 'year is out of range')

    @parameterized.expand([
        param('несколько секунд назад', boundary={'seconds': 45}, period='day'),
        param('há alguns segundos', boundary={'seconds': 45}, period='day'),
    ])
    def test_inexplicit_dates(self, date_string, boundary, period):
        self.given_parser()
        self.given_date_string(date_string)
        self.when_date_is_parsed()
        self.then_error_was_not_raised()
        self.then_date_was_parsed_by_freshness_parser()
        self.then_period_is(period)
        self.then_date_obj_is_between(self.now - timedelta(**boundary), self.now)

    @parameterized.expand([
        param('Today at 9 pm', date(2014, 9, 1), time(21, 0)),
        param('Today at 11:20 am', date(2014, 9, 1), time(11, 20)),
        param('Yesterday 1:20 pm', date(2014, 8, 31), time(13, 20)),
        param('the day before yesterday 16:50', date(2014, 8, 30), time(16, 50)),
        param('2 Tage 18:50', date(2014, 8, 30), time(18, 50)),
        param('1 day ago at 2 PM', date(2014, 8, 31), time(14, 0)),
    ])
    def test_freshness_date_with_time(self, date_string, date, time):
        self.given_parser()
        self.given_date_string(date_string)
        self.when_date_is_parsed()
        self.then_date_is(date)
        self.then_time_is(time)

    def given_date_string(self, date_string):
        self.date_string = date_string

    def given_parser(self):
        self.add_patch(patch.object(freshness_date_parser, 'now', self.now))

        def collecting_get_date_data(get_date_data):
            @wraps(get_date_data)
            def wrapped(date_string):
                self.freshness_result = get_date_data(date_string)
                return self.freshness_result
            return wrapped
        self.add_patch(patch.object(freshness_date_parser,
                                    'get_date_data',
                                    collecting_get_date_data(freshness_date_parser.get_date_data)))

        self.freshness_parser = Mock(wraps=freshness_date_parser)
        self.add_patch(patch('dateparser.date.freshness_date_parser', new=self.freshness_parser))
        self.parser = DateDataParser()

    def when_date_is_parsed(self):
        try:
            self.result = self.parser.get_date_data(self.date_string)
        except Exception as error:
            self.exception = error

    def then_date_is(self, date):
        self.assertEqual(date, self.result['date_obj'].date())

    def then_time_is(self, time):
        self.assertEqual(time, self.result['date_obj'].time())

    def then_period_is(self, period):
        self.assertEqual(period, self.result['period'])

    def then_date_obj_is_between(self, low_boundary, high_boundary):
        self.assertGreater(self.result['date_obj'], low_boundary)
        self.assertLess(self.result['date_obj'], high_boundary)

    def then_date_obj_is_exactly_this_time_ago(self, ago):
        self.assertEqual(self.now - relativedelta(**ago), self.result['date_obj'])

    def then_date_was_not_parsed(self):
        self.assertIsNone(self.result['date_obj'], '"%s" should not be parsed' % self.date_string)

    def then_date_was_parsed_by_freshness_parser(self):
        self.assertEqual(self.result, self.freshness_result)

    def then_error_was_not_raised(self):
        self.assertEqual(NotImplemented, self.exception)

    def then_error_was_raised(self, error_cls, expected_regexp=None):
        self.assertIsInstance(self.exception, error_cls)

        if expected_regexp is None:
            return

        if isinstance(expected_regexp, basestring):
            expected_regexp = re.compile(expected_regexp)

        if not expected_regexp.search(str(self.exception)):
            raise self.failureException('"%s" does not match "%s"' % (expected_regexp.pattern, str(self.exception)))
开发者ID:mevigour,项目名称:dateparser,代码行数:104,代码来源:test_freshness_date_parser.py

示例7: TestFreshnessDateDataParser

# 需要导入模块: from dateparser.date import DateDataParser [as 别名]
# 或者: from dateparser.date.DateDataParser import get_date_data [as 别名]

#.........这里部分代码省略.........
        param('1 week ago at 12:00 am', date(2014, 8, 25), time(0, 0)),
    ])
    def test_freshness_date_with_time(self, date_string, date, time):
        self.given_parser()
        self.given_date_string(date_string)
        self.when_date_is_parsed()
        self.then_date_is(date)
        self.then_time_is(time)

    @parameterized.expand([
        param('2 hours ago', 'Asia/Karachi', date(2014, 9, 1), time(13, 30)),
        param('3 hours ago', 'Europe/Paris', date(2014, 9, 1), time(9, 30)),
        param('5 hours ago', 'US/Eastern', date(2014, 9, 1), time(1, 30)), # date in DST range
        param('Today at 9 pm', 'Asia/Karachi', date(2014, 9, 1), time(21, 0)), # time given, hence, no shift applies
    ])
    def test_freshness_date_with_pytz_timezones(self, date_string, timezone, date, time):
        self.given_parser(settings={'TIMEZONE': timezone})
        self.given_date_string(date_string)
        self.when_date_is_parsed()
        self.then_date_is(date)
        self.then_time_is(time)

    @parameterized.expand([
        param('2 hours ago', 'PKT', date(2014, 9, 1), time(13, 30)),
        param('5 hours ago', 'EST', date(2014, 9, 1), time(0, 30)),
        param('3 hours ago', 'MET', date(2014, 9, 1), time(8, 30)),
    ])
    def test_freshness_date_with_timezone_abbreviations(self, date_string, timezone, date, time):
        self.given_parser(settings={'TIMEZONE': timezone})
        self.given_date_string(date_string)
        self.when_date_is_parsed()
        self.then_date_is(date)
        self.then_time_is(time)

    @parameterized.expand([
        param('2 hours ago', '+05:00', date(2014, 9, 1), time(13, 30)),
        param('5 hours ago', '-05:00', date(2014, 9, 1), time(0, 30)),
        param('3 hours ago', '+01:00', date(2014, 9, 1), time(8, 30)),
    ])
    def test_freshness_date_with_timezone_utc_offset(self, date_string, timezone, date, time):
        self.given_parser(settings={'TIMEZONE': timezone})
        self.given_date_string(date_string)
        self.when_date_is_parsed()
        self.then_date_is(date)
        self.then_time_is(time)

    def given_date_string(self, date_string):
        self.date_string = date_string

    def given_parser(self, settings=None):

        def collecting_get_date_data(get_date_data):
            @wraps(get_date_data)
            def wrapped(*args, **kwargs):
                self.freshness_result = get_date_data(*args, **kwargs)
                return self.freshness_result
            return wrapped
        self.add_patch(patch.object(freshness_date_parser,
                                    'get_date_data',
                                    collecting_get_date_data(freshness_date_parser.get_date_data)))

        self.freshness_parser = Mock(wraps=freshness_date_parser)
        self.add_patch(patch.object(self.freshness_parser, 'now', self.now))

        dt_mock = Mock(wraps=dateparser.freshness_date_parser.datetime)
        dt_mock.utcnow = Mock(return_value=self.now)
        self.add_patch(patch('dateparser.freshness_date_parser.datetime', new=dt_mock))
        self.add_patch(patch('dateparser.date.freshness_date_parser', new=self.freshness_parser))
        self.parser = DateDataParser(settings=settings)

    def when_date_is_parsed(self):
        try:
            self.result = self.parser.get_date_data(self.date_string)
        except Exception as error:
            self.error = error

    def then_date_is(self, date):
        self.assertEqual(date, self.result['date_obj'].date())

    def then_time_is(self, time):
        self.assertEqual(time, self.result['date_obj'].time())

    def then_period_is(self, period):
        self.assertEqual(period, self.result['period'])

    def then_date_obj_is_between(self, low_boundary, high_boundary):
        self.assertGreater(self.result['date_obj'], low_boundary)
        self.assertLess(self.result['date_obj'], high_boundary)

    def then_date_obj_is_exactly_this_time_ago(self, ago):
        self.assertEqual(self.now - relativedelta(**ago), self.result['date_obj'])

    def then_date_was_not_parsed(self):
        self.assertIsNone(self.result['date_obj'], '"%s" should not be parsed' % self.date_string)

    def then_date_was_parsed_by_freshness_parser(self):
        self.assertEqual(self.result, self.freshness_result)

    def then_error_was_not_raised(self):
        self.assertEqual(NotImplemented, self.error)
开发者ID:benjaoming,项目名称:dateparser,代码行数:104,代码来源:test_freshness_date_parser.py

示例8: _parser_get_date

# 需要导入模块: from dateparser.date import DateDataParser [as 别名]
# 或者: from dateparser.date.DateDataParser import get_date_data [as 别名]
 def _parser_get_date(self, date_string, date_formats, languages):
     parser = DateDataParser(languages)
     return parser.get_date_data(date_string, date_formats)
开发者ID:danielmoniz,项目名称:dateparser,代码行数:5,代码来源:hijri.py

示例9: Reminder

# 需要导入模块: from dateparser.date import DateDataParser [as 别名]
# 或者: from dateparser.date.DateDataParser import get_date_data [as 别名]
class Reminder():

    def __init__(self, config=None):
        self.active_reminder = {}
        self.regex = r'\[(.*)\]'
        self.settings = {'PREFER_DATES_FROM': 'future',
                         'DATE_ORDER': 'DMY'}
        self.parser = DateDataParser(languages=['en'],
                                     allow_redetect_language=False,
                                     settings=self.settings)

    async def send_reminder_start_msg(self, user, channel, client, time):
        '''
        Gives an acknowledgement that the reminder has been set.
        '''
        time = time.replace(microsecond=0)
        msg = ":+1: %s I'll remind you at %s UTC." % (user, str(time))
        await client.send_message(channel, msg)

    async def send_reminder_end_msg(self, user, channel, client, text):
        '''
        Sends the message when the reminder finishes with the text
        if it was passed in.
        '''
        if text:
            msg = 'Hello %s, you asked me to remind you of **%s**.' % (user,
                                                                      text)
        else:
            msg = 'Hello %s, you asked me to remind you at this time.' % user
        await client.send_message(channel, msg)

    async def start_reminder_sleep(self, delta, user, channel, client, text, time):
        '''
        Asyncronously sleeps for the reminder length.
        '''
        # Send a message that the reminder is going to be set.
        await self.send_reminder_start_msg(user, channel, client, time)
        await asyncio.sleep(delta.total_seconds())
        await self.send_reminder_end_msg(user, channel, client, text)

    def apply_regex(self, msg):
        '''
        Applies the regex to check if the user passed
        in a optional string in square brackets.
        Returns the original message with the string
        removed and the captured msg.
        '''
        regex_result = re.search(self.regex, msg)
        if regex_result:
            msg = re.sub(self.regex, '', msg).strip()
            return msg, regex_result.group(1)
        else:
            return False

    def parse_msg(self, msg, user):
        '''
        Parses the message passed along with the !remind command.
        Uses the dateparser library to check if the time string
        is valid
        Format: !remindme <time period> [optional string]
        '''
        parsed_time = self.parser.get_date_data(msg)['date_obj']
        if not parsed_time:
            error_msg = ('I could not interept your message %s, try specifing '
                         'the time period in a different format.') % user
            return (False, error_msg)
        now = datetime.utcnow()
        if parsed_time < now:
            error_msg = ("Dont waste my time %s, you can't expect "
                         "me to remind you of an event in the past.") % user
            return (False, error_msg)
        difference = parsed_time - now
        return (True, difference, parsed_time)

    @register('!remindme')
    async def set_reminder(self, msg, user, channel, client, *args, **kwargs):
        '''
        Main function that called to set a reminder. Calls the
        helper functions to parse and to check if its valid.

        If the message is valid, the asyncronous sleep function
        is called.

        Currently loses state on restart ;_; could write/load
        to a file.
        '''
        reminder_txt = None
        optional_string = self.apply_regex(msg)
        if optional_string:
            msg, reminder_txt = optional_string

        parsed_msg = self.parse_msg(msg, user)
        if not parsed_msg[0]:
            return parsed_msg[1]
        else:
            await self.start_reminder_sleep(parsed_msg[1], user,
                                            channel, client, reminder_txt,
                                            parsed_msg[2])
开发者ID:smugporky,项目名称:Yaksha,代码行数:100,代码来源:actions.py

示例10: TestDateParser

# 需要导入模块: from dateparser.date import DateDataParser [as 别名]
# 或者: from dateparser.date.DateDataParser import get_date_data [as 别名]

#.........这里部分代码省略.........
        param('December 2014', today=datetime(2015, 2, 15), expected=datetime(2014, 12, 31)),
    ])
    def test_dates_with_day_missing_prefering_last_day_of_month(self, date_string, today=None, expected=None):
        self.given_configuration('PREFER_DAY_OF_MONTH', 'last')
        self.given_utcnow(today)
        self.given_parser()
        self.given_date_string(date_string)
        self.when_date_is_parsed()
        self.then_date_was_parsed_by_date_parser()
        self.then_date_obj_exactly_is(expected)

    @parameterized.expand([
        param('February 2015', today=datetime(2015, 1, 8), expected=datetime(2015, 2, 1)),
        param('February 2012', today=datetime(2015, 1, 7), expected=datetime(2012, 2, 1)),
        param('March 2015', today=datetime(2015, 1, 25), expected=datetime(2015, 3, 1)),
        param('April 2015', today=datetime(2015, 1, 15), expected=datetime(2015, 4, 1)),
        param('April 2015', today=datetime(2015, 2, 28), expected=datetime(2015, 4, 1)),
        param('December 2014', today=datetime(2015, 2, 15), expected=datetime(2014, 12, 1)),
    ])
    def test_dates_with_day_missing_prefering_first_day_of_month(self, date_string, today=None, expected=None):
        self.given_configuration('PREFER_DAY_OF_MONTH', 'first')
        self.given_utcnow(today)
        self.given_parser()
        self.given_date_string(date_string)
        self.when_date_is_parsed()
        self.then_date_was_parsed_by_date_parser()
        self.then_date_obj_exactly_is(expected)

    @parameterized.expand([
        param(prefer_day_of_month='current'),
        param(prefer_day_of_month='last'),
        param(prefer_day_of_month='first'),
    ])
    def test_that_day_preference_does_not_affect_dates_with_explicit_day(self, prefer_day_of_month=None):
        self.given_configuration('PREFER_DAY_OF_MONTH', prefer_day_of_month)
        self.given_utcnow(datetime(2015, 2, 12))
        self.given_parser()
        self.given_date_string('24 April 2012')
        self.when_date_is_parsed()
        self.then_date_was_parsed_by_date_parser()
        self.then_date_obj_exactly_is(datetime(2012, 4, 24))

    @parameterized.expand([
        param('29 February 2015'),
        param('32 January 2015'),
        param('31 April 2015'),
        param('31 June 2015'),
        param('31 September 2015'),
    ])
    def test_error_should_be_raised_for_invalid_dates_with_too_large_day_number(self, date_string):
        with self.assertRaisesRegexp(ValueError, 'Day not in range for month'):
            DateParser().parse(date_string)

    def given_utcnow(self, now):
        datetime_mock = Mock(wraps=datetime)
        datetime_mock.utcnow = Mock(return_value=now)
        self.add_patch(patch('dateparser.date_parser.datetime', new=datetime_mock))

    def given_local_tz_offset(self, offset):
        self.add_patch(
            patch.object(dateparser.timezone_parser,
                         'local_tz_offset',
                         new=timedelta(seconds=3600 * offset))
        )

    def given_date_string(self, date_string):
        self.date_string = date_string

    def given_parser(self):
        def collecting_get_date_data(parse):
            @wraps(parse)
            def wrapped(date_string):
                self.date_result = parse(date_string)
                return self.date_result
            return wrapped
        self.add_patch(patch.object(date_parser,
                                    'parse',
                                    collecting_get_date_data(date_parser.parse)))

        self.date_parser = Mock(wraps=date_parser)
        self.add_patch(patch('dateparser.date.date_parser', new=self.date_parser))
        self.parser = DateDataParser()

    def given_configuration(self, key, value):
        self.add_patch(patch.object(settings, key, new=value))

    def when_date_is_parsed(self):
        self.result = self.parser.get_date_data(self.date_string)

    def then_period_is(self, period):
        self.assertEqual(period, self.result['period'])

    def then_date_obj_exactly_is(self, expected):
        self.assertEqual(expected, self.result['date_obj'])

    def then_date_was_not_parsed(self):
        self.assertIsNone(self.result['date_obj'], '"%s" should not be parsed' % self.date_string)

    def then_date_was_parsed_by_date_parser(self):
        self.assertEqual(self.result['date_obj'], self.date_result)
开发者ID:mevigour,项目名称:dateparser,代码行数:104,代码来源:test_date_parser.py

示例11: parse

# 需要导入模块: from dateparser.date import DateDataParser [as 别名]
# 或者: from dateparser.date.DateDataParser import get_date_data [as 别名]
    try:
        fmt = params[0]['value']
    except Exception, e:
        pass

    if fmt:
        try:
            d = parse(value)
            value = arrow.get(d, 'Asia/Shanghai').format(fmt)
        except Exception, e:
            try:
                value = arrow.get(value, 'Asia/Shanghai').format(fmt)
            except Exception, e:
                try:
                    ddp = DateDataParser()
                    ret = ddp.get_date_data(value)
                    dateobj = ret['date_obj']
                    ts = arrow.get(dateobj).timestamp + 8 * 60 * 60
                    value = arrow.get(ts).format(fmt)
                except Exception, e:
                    pass

    return value


def substrFilter(value, params=None):
    p = p1 = None
    try:
        p = params[0]['value']
        p1 = params[1]['value']
    except Exception, e:
开发者ID:PixelTool,项目名称:pixelpy,代码行数:33,代码来源:filters.py


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