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


Python iso8601.parse_date方法代码示例

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


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

示例1: calendar_data

# 需要导入模块: import iso8601 [as 别名]
# 或者: from iso8601 import parse_date [as 别名]
def calendar_data(request):
    """
    AJAX JSON results for the calendar (rendered by dashboard.views.calendar)
    """
    try:
        st = iso8601.parse_date(request.GET['start'])
        en = iso8601.parse_date(request.GET['end'])
    except (KeyError, ValueError, iso8601.ParseError):
        return NotFoundResponse(request, errormsg="Bad request")

    user = get_object_or_404(Person, userid=request.user.username)
    local_tz = pytz.timezone(settings.TIME_ZONE)
    start = st - datetime.timedelta(days=1)
    end = en + datetime.timedelta(days=1)

    resp = HttpResponse(content_type="application/json")
    events = _calendar_event_data(user, start, end, local_tz, dt_string=True, colour=True,
            due_before=datetime.timedelta(minutes=1), due_after=datetime.timedelta(minutes=30))
    json.dump(list(events), resp, indent=1)
    return resp 
开发者ID:sfu-fas,项目名称:coursys,代码行数:22,代码来源:views.py

示例2: _offering_meeting_time_data

# 需要导入模块: import iso8601 [as 别名]
# 或者: from iso8601 import parse_date [as 别名]
def _offering_meeting_time_data(request, offering):
    """
    fullcalendar.js data for this offering's events
    """
    try:
        st = iso8601.parse_date(request.GET['start'])
        en = iso8601.parse_date(request.GET['end'])
    except (KeyError, ValueError, iso8601.ParseError):
        return NotFoundResponse(request, errormsg="Bad request")

    local_tz = pytz.timezone(settings.TIME_ZONE)
    start = st - datetime.timedelta(days=1)
    end = en + datetime.timedelta(days=1)

    response = HttpResponse(content_type='application/json')
    data = list(_offerings_calendar_data([offering], None, start, end, local_tz,
                                         dt_string=True, colour=True, browse_titles=True))
    json.dump(data, response, indent=1)
    return response 
开发者ID:sfu-fas,项目名称:coursys,代码行数:21,代码来源:views.py

示例3: clear_expired_members_from_cache

# 需要导入模块: import iso8601 [as 别名]
# 或者: from iso8601 import parse_date [as 别名]
def clear_expired_members_from_cache():
        """ Remove any files from the cache if they've expired. """

        cache_location = CachedQuery.cache_location() 
        CachedQuery.logger.log( "Looking for expired cache members in " + cache_location )
        if not os.path.isdir(cache_location):
            CachedQuery.logger.log( "Cache directory not found.")
            return
        for cache_file in os.listdir(cache_location):
            cache_file = os.path.join(cache_location, cache_file )
            if cache_file.endswith('.query') and os.path.isfile( cache_file ):
                with open(cache_file, 'r') as f:
                    obj = json.loads( f.read() ) 
                    expires = iso8601.parse_date(obj['expires'])
                    if not pytz.UTC.localize(datetime.datetime.now()) < expires:
                        result_file = cache_file.replace('.query', '.result')
                        os.remove( cache_file ) 
                        os.remove( result_file )
                        CachedQuery.logger.log( "Deleting expired cache: " + cache_file + ", " + result_file ) 
开发者ID:sfu-fas,项目名称:coursys,代码行数:21,代码来源:query.py

示例4: get_time

# 需要导入模块: import iso8601 [as 别名]
# 或者: from iso8601 import parse_date [as 别名]
def get_time(item):
    """
    >>> date = get_time({"time": "2015-01-04T15:40:44Z"}) # doctest: +NORMALIZE_WHITESPACE
    >>> date.utctimetuple()  # doctest: +NORMALIZE_WHITESPACE
    time.struct_time(tm_year=2015, tm_mon=1, tm_mday=4, tm_hour=15, tm_min=40,
                     tm_sec=44, tm_wday=6, tm_yday=4, tm_isdst=0)

    >>> date = get_time({"date": "2015-01-04T15:40:44Z"})
    >>> date.utctimetuple()  # doctest: +NORMALIZE_WHITESPACE
    time.struct_time(tm_year=2015, tm_mon=1, tm_mday=4, tm_hour=15, tm_min=40,
                     tm_sec=44, tm_wday=6, tm_yday=4, tm_isdst=0)

    >>> date = get_time({})
    >>> date.utctimetuple()  # doctest: +NORMALIZE_WHITESPACE
    time.struct_time(tm_year=0, tm_mon=12, tm_mday=31, tm_hour=21, tm_min=58,
                     tm_sec=0, tm_wday=6, tm_yday=366, tm_isdst=0)
    """
    if item.get('time', ''):
        bid_time = iso8601.parse_date(item['time'])
    elif item.get('date', ''):
        bid_time = iso8601.parse_date(item['date'])
    else:
        bid_time = datetime(MINYEAR, 1, 1, tzinfo=timezone('Europe/Kiev'))
    return bid_time 
开发者ID:openprocurement,项目名称:openprocurement.auction,代码行数:26,代码来源:utils.py

示例5: validate_response

# 需要导入模块: import iso8601 [as 别名]
# 或者: from iso8601 import parse_date [as 别名]
def validate_response(self, response: ResponseParser):
        # Check it came from the right place
        if self.entity_id != response.issuer:
            raise CannotHandleAssertion(
                f'Entity ID mismatch {self.entity_id} != {response.issuer}')

        if response.conditions is not None:
            # Validate the NotBefore/NotOnOrAfter tags
            now = utcnow()
            not_before = response.conditions.get('NotBefore')
            not_on_or_after = response.conditions.get('NotOnOrAfter')
            try:
                if not_before is not None and now < iso8601.parse_date(not_before):
                    raise CannotHandleAssertion(f'NotBefore={not_before} check failed')
                if not_on_or_after is not None and now >= iso8601.parse_date(not_on_or_after):
                    raise CannotHandleAssertion(f'NotOnOrAfter={not_on_or_after} check failed')
            except ValueError as err:
                raise CannotHandleAssertion("Could not parse date") from err

            # Validate the AudienceRestriction elements, if they exist
            audiences = response._xpath(response.conditions, './saml:AudienceRestriction/saml:Audience')
            entity_id = self.sp.get_sp_entity_id()
            if len(audiences) and not any(el.text == entity_id for el in audiences):
                raise CannotHandleAssertion("No valid AudienceRestriction found") 
开发者ID:timheap,项目名称:flask-saml2,代码行数:26,代码来源:idphandler.py

示例6: value

# 需要导入模块: import iso8601 [as 别名]
# 或者: from iso8601 import parse_date [as 别名]
def value(self):
        if self.option:
            value = self.option.text or ''
            if self.option.additional_input and self.text:
                value += ': ' + self.text
            return value

        elif self.text:
            if self.value_type == VALUE_TYPE_DATETIME:
                try:
                    return iso8601.parse_date(self.text).date()
                except iso8601.ParseError:
                    return self.text
            elif self.value_type == VALUE_TYPE_BOOLEAN:
                if self.text == '1':
                    return _('Yes')
                else:
                    return _('No')
            else:
                return self.text
        else:
            return None 
开发者ID:rdmorganiser,项目名称:rdmo,代码行数:24,代码来源:models.py

示例7: get_date_strings

# 需要导入模块: import iso8601 [as 别名]
# 或者: from iso8601 import parse_date [as 别名]
def get_date_strings(timestamp, precision):
    """Given a timestamp and a wikidata date precision, returns a combination of strings"""
    if timestamp:
        timesplit = timestamp.split('^')[0]
        precisionsplit = precision.split('^')[0]
        date = iso8601.parse_date(timesplit).date()

        if precisionsplit == "11":
            return [
                str(date.year),
                '%s%s' % (date.year, date.month),
                '%s%s%s' % (date.year, date.month, date.day),
            ]
        elif precisionsplit == "10":
            return [str(date.year), '%s%s' % (date.year, date.month)]
        else:
            return [str(date.year)]
    else:
        return [] 
开发者ID:Wikidata,项目名称:soweego,代码行数:21,代码来源:sample_additional_info.py

示例8: deserialize

# 需要导入模块: import iso8601 [as 别名]
# 或者: from iso8601 import parse_date [as 别名]
def deserialize(self, f):
        s = f.read()
        data = json.loads(s)

        def complexify_process(p):
            process = Process(p["pid"], p["ppid"], p["cmdline"], p["ppname"], p["hashes"], p["path"], p["user"], p["domain"], p["logonid"], p["computer"],
                    pid_formatter=self.pid_formatter)
            process.begin = iso8601.parse_date(p["begin"]).replace(tzinfo=None)
            process.end = iso8601.parse_date(p["end"]).replace(tzinfo=None)
            process.parent = p["parent"]
            process.children = p["children"]
            process.notes = p["notes"]
            process.id = p["id"]
            return process

        self._defs = {p["id"]:complexify_process(p) for p in data["definitions"].values()}
        self._roots = data["roots"] 
开发者ID:williballenthin,项目名称:process-forest,代码行数:19,代码来源:process_forest.py

示例9: _coerce_type

# 需要导入模块: import iso8601 [as 别名]
# 或者: from iso8601 import parse_date [as 别名]
def _coerce_type(self, t, value):
        ''' Returns a two-tuple (is_valid, new_value) where new_value is properly coerced. '''
        try:
            if t == 'number':
                return type(value) != bool, float(value)
            elif t == 'integer':
                return type(value) != bool, int(value)
            elif t == 'boolean':
                return type(value) == bool, value
            elif t == 'timestamp':
                if type(value) == datetime.datetime:
                    return True, value
                return True, iso8601.parse_date(value)
            elif t == 'date':
                if type(value) == datetime.date:
                    return True, value
                return True, datetime.date(*(int(z) for z in value.split('-')))
            elif t == 'string':
                # Allow coercing ints/floats, but nothing else
                return type(value) in [str, int, float], str(value)
            elif t == 'enum':
                return type(value) == str, str(value)
        except:
            pass
        return False, None 
开发者ID:better,项目名称:jsonschema2db,代码行数:27,代码来源:jsonschema2db.py

示例10: as_dict

# 需要导入模块: import iso8601 [as 别名]
# 或者: from iso8601 import parse_date [as 别名]
def as_dict(self):
        details = json.loads(self.details)
        name = "Anonymous"
        amount = " ".join([str(details['amount']), details['currencyCode']])
        if 'user' in details:
            name = details['user']['displayName']
        elif 'username' in details:
            name = details['username']
        timestamp = iso8601.parse_date(details['date'])
        info = {
            'name': name,
            'amount': amount,
            'comment': details['note'],
            'donation_amount': float(details['amount']),
            'currency': details['currencyCode'],
            'timestamp': timestamp,
        }
        return info 
开发者ID:google,项目名称:mirandum,代码行数:20,代码来源:models.py

示例11: as_dict

# 需要导入模块: import iso8601 [as 别名]
# 或者: from iso8601 import parse_date [as 别名]
def as_dict(self):
        details = json.loads(self.details)
        name = "Anonymous Donor"
        if 'donorName' in details and details['donorName']:
            name = details['donorName']
        datetime = iso8601.parse_date(details['createdOn'])    
        info = {
            # general 
            'name': name,
            'comment': details.get('message', "") or '',
            'donation_amount': float(details['donationAmount']),
            'currency': 'USD',
            # Display-friendly
            'amount': "$%.2f" % details['donationAmount'],
            'timestamp': datetime,
        }
        return info 
开发者ID:google,项目名称:mirandum,代码行数:19,代码来源:models.py

示例12: as_dict

# 需要导入模块: import iso8601 [as 别名]
# 或者: from iso8601 import parse_date [as 别名]
def as_dict(self):
        details = json.loads(self.details)
        name = "Anonymous Donor"
        if 'supporterDetails' in details['snippet']:
            name = details['snippet']['supporterDetails']['displayName']
        datetime = iso8601.parse_date(details['snippet']['createdAt'])    
        info = {
            # general 
            'name': name,
            'comment': details['snippet'].get('commentText', ""),
            'donation_amount': float(details['snippet']['amountMicros']) / 1000000.,
            'currency': details['snippet']['currency'],
            
            # Display-friendly
            'amount': details['snippet']['displayString'],
            
            # Filtering friendly
            'amount_micros': int(details['snippet']['amountMicros']),

            'timestamp': datetime,
        }
        return info 
开发者ID:google,项目名称:mirandum,代码行数:24,代码来源:models.py

示例13: _timestamp_parse

# 需要导入模块: import iso8601 [as 别名]
# 或者: from iso8601 import parse_date [as 别名]
def _timestamp_parse(ts_in: ConvertableTimestamp) -> datetime:
    """
    Takes something representing a timestamp and
    returns a timestamp in the representation we want.
    """
    ts = iso8601.parse_date(ts_in) if isinstance(ts_in, str) else ts_in
    # Set resolution to milliseconds instead of microseconds
    # (Fixes incompability with software based on unix time, for example mongodb)
    ts = ts.replace(microsecond=int(ts.microsecond / 1000) * 1000)
    # Add timezone if not set
    if not ts.tzinfo:
        # Needed? All timestamps should be iso8601 so ought to always contain timezone.
        # Yes, because it is optional in iso8601
        logger.warning("timestamp without timezone found, using UTC: {}".format(ts))
        ts = ts.replace(tzinfo=timezone.utc)
    return ts 
开发者ID:ActivityWatch,项目名称:aw-core,代码行数:18,代码来源:models.py

示例14: test_query2_query_function_calling

# 需要导入模块: import iso8601 [as 别名]
# 或者: from iso8601 import parse_date [as 别名]
def test_query2_query_function_calling():
    qname = "asd"
    starttime = iso8601.parse_date("1970-01-01")
    endtime = iso8601.parse_date("1970-01-02")

    # Function which doesn't exist
    with pytest.raises(QueryInterpretException):
        example_query = "RETURN = asd();"
        query(qname, example_query, starttime, endtime, None)

    # Function which does exist with invalid arguments
    with pytest.raises(QueryInterpretException):
        example_query = "RETURN = nop(badarg);"
        query(qname, example_query, starttime, endtime, None)

    # Function which does exist with valid arguments
    example_query = "RETURN = nop();"
    query(qname, example_query, starttime, endtime, None) 
开发者ID:ActivityWatch,项目名称:aw-core,代码行数:20,代码来源:test_query2.py

示例15: test_query2_return_value

# 需要导入模块: import iso8601 [as 别名]
# 或者: from iso8601 import parse_date [as 别名]
def test_query2_return_value():
    qname = "asd"
    starttime = iso8601.parse_date("1970-01-01")
    endtime = iso8601.parse_date("1970-01-02")
    example_query = "RETURN = 1;"
    result = query(qname, example_query, starttime, endtime, None)
    assert result == 1

    example_query = "RETURN = 'testing 123'"
    result = query(qname, example_query, starttime, endtime, None)
    assert result == "testing 123"

    example_query = "RETURN = {'a': 1}"
    result = query(qname, example_query, starttime, endtime, None)
    assert result == {"a": 1}

    # Nothing to return
    with pytest.raises(QueryParseException):
        example_query = "a=1"
        result = query(qname, example_query, starttime, endtime, None) 
开发者ID:ActivityWatch,项目名称:aw-core,代码行数:22,代码来源:test_query2.py


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