Python dateutil.parser.parse() Examples

The following are 30 code examples for showing how to use dateutil.parser.parse(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module dateutil.parser , or try the search function .

Example 1
Project: aegea   Author: kislyuk   File: __init__.py    License: Apache License 2.0 8 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
Project: figures   Author: appsembler   File: test_course_enrollment_view.py    License: 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 3
Project: figures   Author: appsembler   File: helpers.py    License: 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 4
Project: figures   Author: appsembler   File: helpers.py    License: 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 5
Project: faxplus-python   Author: alohi   File: api_client.py    License: 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 6
Project: faxplus-python   Author: alohi   File: api_client.py    License: 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 7
Project: sato   Author: megagonlabs   File: type_detection.py    License: 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 8
Project: plugin.video.emby   Author: MediaBrowser   File: test_parser.py    License: 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 9
Project: plugin.video.emby   Author: MediaBrowser   File: test_parser.py    License: 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 10
Project: cyberdisc-bot   Author: CyberDiscovery   File: cyber.py    License: MIT License 5 votes vote down vote up
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}!"
        ) 
Example 11
Project: fishroom   Author: tuna   File: helpers.py    License: GNU General Public License v3.0 5 votes vote down vote up
def string_date_time(dstr):
    d = parser.parse(dstr).astimezone(tz)
    return d.strftime("%Y-%m-%d"), d.strftime("%H:%M:%S") 
Example 12
Project: figures   Author: appsembler   File: test_site_daily_metrics_view.py    License: MIT License 5 votes vote down vote up
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) 
Example 13
Project: figures   Author: appsembler   File: test_site_daily_metrics_view.py    License: MIT License 5 votes vote down vote up
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) 
Example 14
Project: figures   Author: appsembler   File: test_course_daily_metrics_view.py    License: MIT License 5 votes vote down vote up
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) 
Example 15
Project: figures   Author: appsembler   File: test_course_daily_metrics_view.py    License: MIT License 5 votes vote down vote up
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 
Example 16
Project: figures   Author: appsembler   File: test_filters.py    License: MIT License 5 votes vote down vote up
def test_get_by_date(self):
        the_date_str = '2018-01-02'
        the_date = dateutil_parse(the_date_str).date()

        f = SiteDailyMetricsFilter(
            queryset=SiteDailyMetrics.objects.filter(date_for=the_date))

        self.assertQuerysetEqual(
            f.qs,
            [o.id for o in self.site_daily_metrics if o.date_for == the_date],
            lambda o: o.id, ordered=False) 
Example 17
Project: figures   Author: appsembler   File: test_filters.py    License: MIT License 5 votes vote down vote up
def test_get_by_date(self):
        the_date_str = '2018-01-02'
        the_date = dateutil_parse(the_date_str).date()

        f = CourseMauMetricsFilter(
            queryset=CourseMauMetrics.objects.filter(date_for=the_date))

        self.assertQuerysetEqual(
            f.qs,
            [o.id for o in self.models if o.date_for == the_date],
            lambda o: o.id, ordered=False) 
Example 18
Project: figures   Author: appsembler   File: test_filters.py    License: MIT License 5 votes vote down vote up
def test_get_by_date(self):
        the_date_str = '2018-01-02'
        the_date = dateutil_parse(the_date_str).date()

        f = SiteMauMetricsFilter(
            queryset=SiteMauMetrics.objects.filter(date_for=the_date))

        self.assertQuerysetEqual(
            f.qs,
            [o.id for o in self.models if o.date_for == the_date],
            lambda o: o.id, ordered=False) 
Example 19
Project: figures   Author: appsembler   File: test_serializers.py    License: MIT License 5 votes vote down vote up
def test_has_fields(self):
        data = self.serializer.data
        assert set(data.keys()) == set(self.expected_fields)

        # This is to make sure that the serializer retrieves the correct nested
        # model (UserProfile) data
        assert data['course_id'] == str(self.course_overview.id)
        assert data['course_name'] == self.course_overview.display_name
        assert data['course_code'] == self.course_overview.number
        assert data['org'] == self.course_overview.org
        assert parse(data['start_date']) == self.course_overview.start
        assert parse(data['end_date']) == self.course_overview.end
        assert data['self_paced'] == self.course_overview.self_paced 
Example 20
Project: figures   Author: appsembler   File: test_serializers.py    License: MIT License 5 votes vote down vote up
def test_has_fields(self):
        '''Tests that the serialized general course  data has specific keys and values
        '''
        data = self.serializer.data
        assert set(data.keys()) == set(self.expected_fields)

        # This is to make sure that the serializer retrieves the correct nested
        # model (UserProfile) data
        assert data['course_id'] == str(self.course_overview.id)
        assert data['course_name'] == self.course_overview.display_name
        assert data['course_code'] == self.course_overview.number
        assert data['org'] == self.course_overview.org
        assert parse(data['start_date']) == self.course_overview.start
        assert parse(data['end_date']) == self.course_overview.end
        assert data['self_paced'] == self.course_overview.self_paced 
Example 21
Project: figures   Author: appsembler   File: test_helpers.py    License: MIT License 5 votes vote down vote up
def test_get_now_from_unicode(self):
        format = '%Y-%m-%d %H:%M:%S'
        a_datetime_str = unicode(self.now.strftime(format))
        expected = dateutil_parse(a_datetime_str).replace(tzinfo=utc)
        assert isinstance(a_datetime_str, unicode)
        assert as_datetime(a_datetime_str) == expected 
Example 22
Project: cert-verifier   Author: blockchain-certificates   File: __init__.py    License: MIT License 5 votes vote down vote up
def parse_or_none(time):
    if time is None:
        return None
    try:
        parsed_date = parse(time)
    except:
        # try parsing as unix ms
        parsed_date = datetime.datetime.fromtimestamp(time)

    utc = pytz.UTC
    if parsed_date.tzinfo is None or parsed_date.tzinfo.utcoffset(parsed_date) is None:
        parsed_date = utc.localize(parsed_date)
    return parsed_date 
Example 23
Project: Matrix-NEB   Author: matrix-org   File: time_utils.py    License: Apache License 2.0 5 votes vote down vote up
def cmd_encode(self, event, *args):
        """Encode a time. Multiple different formats are supported, e.g. YYYY-MM-DD HH:MM:SS 'time encode <date>'"""
        # use the body directly so spaces are handled correctly.
        date_str = event["content"]["body"][len("!time encode "):]
        
        if date_str.lower().strip() == "now":
            now = time.time()
            return "Parsed as %s\n%s" % (datetime.datetime.utcfromtimestamp(now), now)
        
        try:
            d = parser.parse(date_str)
            ts = calendar.timegm(d.timetuple())
            return "Parsed as %s\n%s" % (d.strftime("%Y-%m-%d %H:%M:%S"), ts)
        except ValueError:
            return "Failed to parse '%s'" % date_str 
Example 24
Project: Matrix-NEB   Author: matrix-org   File: time_utils.py    License: Apache License 2.0 5 votes vote down vote up
def cmd_decode(self, event, timestamp):
        """Decode from a unix timestamp. 'time decode <timestamp>'"""
        is_millis = len(timestamp) > 10
        try:
            ts = int(timestamp)
            if is_millis:
                return datetime.datetime.utcfromtimestamp(ts/1000.0).strftime("%Y-%m-%d %H:%M:%S.%f")
            else:
                return datetime.datetime.utcfromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S")
        except ValueError:
            return "Failed to parse '%s'" % timestamp 
Example 25
Project: python-podman   Author: containers   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def datetime_parse(string):
    """Convert timestamps to datetime.

    tzinfo aware, if provided.
    """
    return dateutil_parse(string.upper(), fuzzy=True) 
Example 26
Project: ripe-atlas-tools   Author: RIPE-NCC   File: validators.py    License: GNU General Public License v3.0 5 votes vote down vote up
def datetime(string):
        try:
            return parser.parse(string)
        except:
            raise argparse.ArgumentTypeError(
                "Times must be specified in ISO 8601 format.  For example: "
                "2010-10-01T00:00:00 or a portion thereof.  All times are in "
                "UTC."
            ) 
Example 27
Project: dino   Author: thenetcircle   File: storage.py    License: Apache License 2.0 5 votes vote down vote up
def format_time_range(self, from_time: str=None, to_time: str=None):
        if not is_blank(from_time):
            try:
                from_time = parser.parse(from_time).astimezone(tzutc())
            except Exception as e:
                logger.error('invalid from time "%s": %s' % (str(from_time), str(e)))
                raise RuntimeError('invalid from time "%s": %s' % (str(to_time), str(e)))
        else:
            from_time = None

        if not is_blank(to_time):
            try:
                to_time = parser.parse(to_time).astimezone(tzutc())
            except Exception as e:
                logger.error('invalid to time "%s": %s' % (str(to_time), str(e)))
                raise RuntimeError('invalid to time "%s": %s' % (str(to_time), str(e)))
        else:
            to_time = None

        if from_time is not None and to_time is not None:
            if from_time > to_time:
                logger.error('from time %s must be before to time %s' % (str(from_time), str(to_time)))
                raise RuntimeError('from time %s must be before to time %s' % (str(from_time), str(to_time)))

        if to_time is not None and from_time is None:
            from_time = to_time - datetime.timedelta(seconds=60*60)
        if from_time is not None and to_time is None:
            to_time = from_time + datetime.timedelta(seconds=60*60)

        if from_time is None or to_time is None:
            to_time = datetime.datetime.utcnow()
            from_time = to_time - datetime.timedelta(days=7)

        return from_time, to_time 
Example 28
Project: watchdog   Author: flipkart-incubator   File: api.py    License: Apache License 2.0 5 votes vote down vote up
def generate_minimal_query(self, f):
    query = []
    # retrieving lists
    if f['rejectedSelect'] == "hide":
      exp = "^(?!\*\* REJECT \*\*\s+DO NOT USE THIS CANDIDATE NUMBER.*)"
      query.append({'summary': re.compile(exp)})

    # cvss logic
    if   f['cvssSelect'] == "above":  query.append({'cvss': {'$gt': float(f['cvss'])}})
    elif f['cvssSelect'] == "equals": query.append({'cvss': float(f['cvss'])})
    elif f['cvssSelect'] == "below":  query.append({'cvss': {'$lt': float(f['cvss'])}})

    # date logic
    if f['timeSelect'] != "all":
      if f['startDate']:
        startDate = parse_datetime(f['startDate'], ignoretz=True, dayfirst=True)
      if f['endDate']:
        endDate   = parse_datetime(f['endDate'],   ignoretz=True, dayfirst=True)

      if   f['timeSelect'] == "from":
        query.append({f['timeTypeSelect']: {'$gt': startDate}})
      elif f['timeSelect'] == "until":
        query.append({f['timeTypeSelect']: {'$lt': endDate}})
      elif f['timeSelect'] == "between":
        query.append({f['timeTypeSelect']: {'$gt': startDate, '$lt': endDate}})
      elif f['timeSelect'] == "outside":
        query.append({'$or': [{f['timeTypeSelect']: {'$lt': startDate}}, {f['timeTypeSelect']: {'$gt': endDate}}]})
    return query 
Example 29
Project: donation-tracker   Author: GamesDoneQuick   File: test_prize.py    License: Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.eventStart = parse_date('2014-01-01 16:00:00Z')
        self.rand = random.Random(516273)
        self.event = randgen.build_random_event(
            self.rand, start_time=self.eventStart, num_donors=100, num_runs=50
        )
        self.runsList = list(models.SpeedRun.objects.filter(event=self.event))
        self.donorList = list(models.Donor.objects.all()) 
Example 30
Project: donation-tracker   Author: GamesDoneQuick   File: test_prize.py    License: Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.eventStart = parse_date('2012-01-01 01:00:00Z')
        self.rand = random.Random()
        self.event = randgen.build_random_event(self.rand, start_time=self.eventStart)
        self.event.save()