Python dateutil.parser.parse() Examples

The following are 30 code examples of dateutil.parser.parse(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module dateutil.parser , or try the search function .
Example #1
Source File: __init__.py    From aegea with Apache License 2.0 9 votes vote down vote up
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)) 
Example #2
Source File: helpers.py    From figures with MIT License 6 votes vote down vote up
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') 
Example #3
Source File: test_parser.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #4
Source File: test_course_enrollment_view.py    From figures with MIT License 6 votes vote down vote up
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 
Example #5
Source File: helpers.py    From figures with MIT License 6 votes vote down vote up
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))) 
Example #6
Source File: test_parser.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
def testParseUnicodeWords(self):

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

        self.assertEqual(parse('10 Сентябрь 2015 10:20',
                               parserinfo=rus_parserinfo()),
                         datetime(2015, 9, 10, 10, 20)) 
Example #7
Source File: api_client.py    From faxplus-python with MIT License 6 votes vote down vote up
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)
            ) 
Example #8
Source File: api_client.py    From faxplus-python with MIT License 6 votes vote down vote up
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)
                )
            ) 
Example #9
Source File: type_detection.py    From sato with Apache License 2.0 6 votes vote down vote up
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 
Example #10
Source File: test_parser.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testISOStrippedFormatStrip3(self):
        self.assertEqual(parse("20030925T1049"),
                         datetime(2003, 9, 25, 10, 49, 0)) 
Example #11
Source File: test_parser.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testDateCommandFormatStrip4(self):
        self.assertEqual(parse("Thu 10:36:28", default=self.default),
                         datetime(2003, 9, 25, 10, 36, 28)) 
Example #12
Source File: test_parser.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testDateCommandFormatStrip5(self):
        self.assertEqual(parse("Sep 10:36:28", default=self.default),
                         datetime(2003, 9, 25, 10, 36, 28)) 
Example #13
Source File: test_parser.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testDateCommandFormatStrip6(self):
        self.assertEqual(parse("10:36:28", default=self.default),
                         datetime(2003, 9, 25, 10, 36, 28)) 
Example #14
Source File: test_parser.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testDateCommandFormatStrip7(self):
        self.assertEqual(parse("10:36", default=self.default),
                         datetime(2003, 9, 25, 10, 36)) 
Example #15
Source File: test_parser.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testDateCommandFormatStrip1(self):
        self.assertEqual(parse("Thu Sep 25 10:36:28 2003"),
                         datetime(2003, 9, 25, 10, 36, 28)) 
Example #16
Source File: test_parser.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testISOStrippedFormatStrip5(self):
        self.assertEqual(parse("20030925"),
                         datetime(2003, 9, 25)) 
Example #17
Source File: test_parser.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testISOStrippedFormatStrip4(self):
        self.assertEqual(parse("20030925T10"),
                         datetime(2003, 9, 25, 10)) 
Example #18
Source File: test_parser.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testPythonLoggerFormat(self):
        self.assertEqual(parse("2003-09-25 10:49:41,502"),
                         datetime(2003, 9, 25, 10, 49, 41, 502000)) 
Example #19
Source File: test_parser.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testISOStrippedFormatStrip1(self):
        self.assertEqual(parse("20030925T104941-0300"),
                         datetime(2003, 9, 25, 10, 49, 41,
                                  tzinfo=self.brsttz)) 
Example #20
Source File: test_parser.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testDateCommandFormatStrip2(self):
        self.assertEqual(parse("Thu Sep 25 10:36:28", default=self.default),
                         datetime(2003, 9, 25, 10, 36, 28)) 
Example #21
Source File: test_parser.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testDateCommandFormatStrip11(self):
        self.assertEqual(parse("Sep", default=self.default),
                         datetime(2003, 9, 25)) 
Example #22
Source File: test_parser.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testDateCommandFormatIgnoreTz(self):
        self.assertEqual(parse("Thu Sep 25 10:36:28 BRST 2003",
                               ignoretz=True),
                         datetime(2003, 9, 25, 10, 36, 28)) 
Example #23
Source File: test_parser.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testDateCommandFormatWithLong(self):
        if not PY3:
            self.assertEqual(parse("Thu Sep 25 10:36:28 BRST 2003",
                                   tzinfos={"BRST": long(-10800)}),
                             datetime(2003, 9, 25, 10, 36, 28,
                                      tzinfo=self.brsttz)) 
Example #24
Source File: test_parser.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testDateCommandFormatReversed(self):
        self.assertEqual(parse("2003 10:36:28 BRST 25 Sep Thu",
                               tzinfos=self.tzinfos),
                         datetime(2003, 9, 25, 10, 36, 28,
                                  tzinfo=self.brsttz)) 
Example #25
Source File: test_parser.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testDateCommandFormat(self):
        self.assertEqual(parse("Thu Sep 25 10:36:28 BRST 2003",
                               tzinfos=self.tzinfos),
                         datetime(2003, 9, 25, 10, 36, 28,
                                  tzinfo=self.brsttz)) 
Example #26
Source File: test_parser.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testParseWithNulls(self):
        # This relies on the from __future__ import unicode_literals, because
        # explicitly specifying a unicode literal is a syntax error in Py 3.2
        # May want to switch to u'...' if we ever drop Python 3.2 support.
        pstring = '\x00\x00August 29, 1924'

        self.assertEqual(parse(pstring),
                         datetime(1924, 8, 29)) 
Example #27
Source File: test_parser.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testParserParseStr(self):
        from dateutil.parser import parser

        self.assertEqual(parser().parse(self.str_str),
                         parser().parse(self.uni_str)) 
Example #28
Source File: test_parser.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testParseBytearray(self):
        # GH #417
        self.assertEqual(parse(bytearray(b'2014 January 19')),
                         datetime(2014, 1, 19)) 
Example #29
Source File: test_parser.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testParseStr(self):
        self.assertEqual(parse(self.str_str),
                         parse(self.uni_str)) 
Example #30
Source File: test_parser.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testParseStream(self):
        dstr = StringIO('2014 January 19')

        self.assertEqual(parse(dstr), datetime(2014, 1, 19))