當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。