python类utc()的实例源码

base.py 文件源码 项目:trydjango18 作者: wei0104 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def adapt_datetime_with_timezone_support(value, conv):
    # Equivalent to DateTimeField.get_db_prep_value. Used only by raw SQL.
    if settings.USE_TZ:
        if timezone.is_naive(value):
            warnings.warn("MySQL received a naive datetime (%s)"
                          " while time zone support is active." % value,
                          RuntimeWarning)
            default_timezone = timezone.get_default_timezone()
            value = timezone.make_aware(value, default_timezone)
        value = value.astimezone(timezone.utc).replace(tzinfo=None)
    return Thing2Literal(value.strftime("%Y-%m-%d %H:%M:%S.%f"), conv)

# MySQLdb-1.2.1 returns TIME columns as timedelta -- they are more like
# timedelta in terms of actual behavior as they are signed and include days --
# and Django expects time, so we still need to override that. We also need to
# add special handling for SafeText and SafeBytes as MySQLdb's type
# checking is too tight to catch those (see Django ticket #6052).
# Finally, MySQLdb always returns naive datetime objects. However, when
# timezone support is active, Django expects timezone-aware datetime objects.
snapshot.py 文件源码 项目:esdc-ce 作者: erigones 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def create_from_zfs_name(cls, zfs_name, status=OK, name=None, timestamp=None, **kwargs):
        """Create new snapshot from info gathered from compute node"""
        t, id = zfs_name.split('-', 1)
        t = t[0]

        if t == TT_EXEC:
            type = cls.MANUAL
        elif t == TT_AUTO:
            type = cls.AUTO
        else:
            raise AssertionError('Unknown snapshot type')

        if not name or name == '-':
            name = zfs_name

        snap = cls(id=int(id), name=name, type=type, status=status, **kwargs)

        if timestamp:
            snap.created = datetime.fromtimestamp(timestamp, timezone.utc)

        snap.save(force_insert=True)

        return snap
utils.py 文件源码 项目:hawkpost 作者: whitesmith 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def key_state(key, gpg):
    if not key:
        return None, "invalid"
    results = gpg.import_keys(key).results
    # Key data is present in the last element of the list
    if not results or not results[-1]["fingerprint"]:
        return None, "invalid"

    key_fingerprint = results[-1]["fingerprint"]

    # Since the keyring is exclusive for this import
    # only the imported key exists in it.
    key = gpg.list_keys()[0]
    exp_timestamp = int(key["expires"]) if key["expires"] else 0
    expires = datetime.fromtimestamp(exp_timestamp, timezone.utc)

    if key["trust"] == "r":
        state = "revoked"
    elif exp_timestamp and expires < timezone.now():
        state = "expired"
    else:
        state = "valid"

    return key_fingerprint, state
test_feed.py 文件源码 项目:wagtailsocialfeed 作者: LUKKIEN 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_feed(self, feed):
        self.assertIsNone(cache.get(self.cache_key))
        stream = self.stream.get_items(config=self.feedconfig)

        self.assertIsNotNone(cache.get(self.cache_key))
        self.assertEqual(len(stream), 12)
        for item in stream:
            assert isinstance(item, FeedItem)
        self.assertEqual(
            stream[0].posted,
            datetime.datetime(2017, 11, 15, 21, 55, 44, tzinfo=timezone.utc))
        self.assertEqual(stream[0].image_dict['small']['src'],
                         "https://scontent-amt2-1.cdninstagram.com/t51.2885-15/s320x320/e35/c86.0.908.908/23507082_173663316554801_3781761610851287040_n.jpg" # NOQA
                         )
        self.assertEqual(stream[0].image_dict['thumb']['src'],
                         "https://scontent-amt2-1.cdninstagram.com/t51.2885-15/s240x240/e35/c86.0.908.908/23507082_173663316554801_3781761610851287040_n.jpg" # NOQA
                         )
        self.assertEqual(stream[0].image_dict['medium']['src'],
                         "https://scontent-amt2-1.cdninstagram.com/t51.2885-15/s480x480/e35/c86.0.908.908/23507082_173663316554801_3781761610851287040_n.jpg" # NOQA
                         )

        # The following data is not explicitly stored, but should still be accessible
        self.assertEqual(stream[0].code, "Bbh7J7JlCRn")
test_feed.py 文件源码 项目:wagtailsocialfeed 作者: LUKKIEN 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def test_feed(self, feed):
        self.assertIsNone(cache.get(self.cache_key))

        stream = self.stream.get_items(config=self.feedconfig)

        self.assertIsNotNone(cache.get(self.cache_key))
        self.assertEqual(len(stream), 25)

        for item in stream:
            self.assertIsInstance(item, FeedItem)
        self.assertEqual(
            stream[0].posted,
            datetime.datetime(2016, 10, 4, 14, 48, 9, tzinfo=timezone.utc))

        self.assertEqual(stream[0].image_dict['thumb']['url'],
                         "https://scontent.xx.fbcdn.net/v/t1.0-0/s130x130/14606290_1103282596374848_3084561525150401400_n.jpg?oh=4a993e12211341d2304724a5822b1fbf&oe=58628491" # NOQA
                         )

        # The following data is not explicitly stored, but should still be accessible
        self.assertEqual(stream[0].icon, "https://www.facebook.com/images/icons/photo.gif")
base.py 文件源码 项目:lifesoundtrack 作者: MTG 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def adapt_datetime_warn_on_aware_datetime(value, conv):
    # Remove this function and rely on the default adapter in Django 2.0.
    if settings.USE_TZ and timezone.is_aware(value):
        warnings.warn(
            "The MySQL database adapter received an aware datetime (%s), "
            "probably from cursor.execute(). Update your code to pass a "
            "naive datetime in the database connection's time zone (UTC by "
            "default).", RemovedInDjango20Warning)
        # This doesn't account for the database connection's timezone,
        # which isn't known. (That's why this adapter is deprecated.)
        value = value.astimezone(timezone.utc).replace(tzinfo=None)
    return Thing2Literal(value.strftime("%Y-%m-%d %H:%M:%S.%f"), conv)

# MySQLdb-1.2.1 returns TIME columns as timedelta -- they are more like
# timedelta in terms of actual behavior as they are signed and include days --
# and Django expects time, so we still need to override that. We also need to
# add special handling for SafeText and SafeBytes as MySQLdb's type
# checking is too tight to catch those (see Django ticket #6052).
base.py 文件源码 项目:lifesoundtrack 作者: MTG 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def timezone(self):
        """
        Time zone for datetimes stored as naive values in the database.

        Returns a tzinfo object or None.

        This is only needed when time zone support is enabled and the database
        doesn't support time zones. (When the database supports time zones,
        the adapter handles aware datetimes so Django doesn't need to.)
        """
        if not settings.USE_TZ:
            return None
        elif self.features.supports_timezones:
            return None
        elif self.settings_dict['TIME_ZONE'] is None:
            return timezone.utc
        else:
            # Only this branch requires pytz.
            return pytz.timezone(self.settings_dict['TIME_ZONE'])
feedgenerator.py 文件源码 项目:lifesoundtrack 作者: MTG 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def latest_post_date(self):
        """
        Returns the latest item's pubdate or updateddate. If no items
        have either of these attributes this returns the current UTC date/time.
        """
        latest_date = None
        date_keys = ('updateddate', 'pubdate')

        for item in self.items:
            for date_key in date_keys:
                item_date = item.get(date_key)
                if item_date:
                    if latest_date is None or item_date > latest_date:
                        latest_date = item_date

        # datetime.now(tz=utc) is slower, as documented in django.utils.timezone.now
        return latest_date or datetime.datetime.utcnow().replace(tzinfo=utc)
util.py 文件源码 项目:mobetta 作者: maykinmedia 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def timestamp_for_metadata(dt=None):
    """
    Return a timestamp with a timezone for the configured locale.  If all else
    fails, consider localtime to be UTC.

    Originally written by Marco Bonetti.
    """
    dt = dt or datetime.datetime.now()
    if timezone is None:
        return dt.strftime('%Y-%m-%d %H:%M%z')
    if not dt.tzinfo:
        tz = timezone.get_current_timezone()
        if not tz:
            tz = timezone.utc
        dt = dt.replace(tzinfo=timezone.get_current_timezone())
    return dt.strftime("%Y-%m-%d %H:%M%z")
test_valid_parking.py 文件源码 项目:parkkihubi 作者: City-of-Helsinki 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def test_time_filtering(operator, staff_api_client, parking_factory, name):
    p1 = parking_factory(
        registration_number='ABC-123',
        time_start=datetime(2012, 1, 1, 12, 0, 0, tzinfo=utc),
        time_end=datetime(2014, 1, 1, 12, 0, 0, tzinfo=utc),
        operator=operator)
    p2 = parking_factory(
        registration_number='ABC-123',
        time_start=datetime(2014, 1, 1, 12, 0, 0, tzinfo=utc),
        time_end=datetime(2016, 1, 1, 12, 0, 0, tzinfo=utc),
        operator=operator)
    p3 = parking_factory(registration_number='ABC-123')

    (time, expected_parkings) = {
        'before_all': ('2000-01-01T12:00:00Z', []),
        'at_start_of_1st': ('2012-01-01T12:00:00Z', [p1]),
        'after_start_of_1st': ('2012-01-01T12:00:01Z', [p1]),
        'before_end_of_1st': ('2014-01-01T11:59:59Z', [p1]),
        'between_1st_and_2nd': ('2014-01-01T12:00:00Z', [p1, p2]),
        'after_start_of_2nd': ('2014-01-01T12:00:01Z', [p2]),
        'before_end_of_2nd': ('2016-01-01T11:59:59Z', [p2]),
        'at_end_of_2nd': ('2016-01-01T12:00:00Z', [p2]),
        'less_than_15min_after_2nd': ('2016-01-01T12:14:59Z', [p2]),
        'more_than_15min_after_2nd': ('2016-01-02T12:15:01Z', []),
        'less_than_day_after_2nd': ('2016-01-01T22:00:00Z', []),
        'more_than_day_after_2nd': ('2016-01-02T13:00:00Z', []),
        'now': ('', [p3]),
    }[name]

    filtering = '&time={}'.format(time) if time else ''
    response = get(staff_api_client, list_url_for_abc + filtering)
    check_response_objects(response, expected_parkings)
base.py 文件源码 项目:mos-horizon 作者: Mirantis 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def get_start(year, month, day):
        start = datetime.datetime(year, month, day, 0, 0, 0)
        return timezone.make_aware(start, timezone.utc)
base.py 文件源码 项目:mos-horizon 作者: Mirantis 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def get_end(year, month, day):
        end = datetime.datetime(year, month, day, 23, 59, 59)
        return timezone.make_aware(end, timezone.utc)
base.py 文件源码 项目:mos-horizon 作者: Mirantis 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def summarize(self, start, end):
        if not api.nova.extension_supported('SimpleTenantUsage', self.request):
            return

        if start <= end and start <= self.today:
            # The API can't handle timezone aware datetime, so convert back
            # to naive UTC just for this last step.
            start = timezone.make_naive(start, timezone.utc)
            end = timezone.make_naive(end, timezone.utc)
            try:
                self.usage_list = self.get_usage_list(start, end)
            except Exception:
                exceptions.handle(self.request,
                                  _('Unable to retrieve usage information.'))
        elif end < start:
            messages.error(self.request,
                           _("Invalid time period. The end date should be "
                             "more recent than the start date."))
        elif start > self.today:
            messages.error(self.request,
                           _("Invalid time period. You are requesting "
                             "data from the future which may not exist."))

        for project_usage in self.usage_list:
            project_summary = project_usage.get_summary()
            for key, value in project_summary.items():
                self.summary.setdefault(key, 0)
                self.summary[key] += value
filemodels.py 文件源码 项目:ecs_sclm 作者: meaningful 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def canonical_time(self):
        if settings.USE_TZ:
            return int((self.uploaded_at - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds())
        else:
            return int((self.uploaded_at - datetime(1970, 1, 1)).total_seconds())
file.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def _last_modification(self):
        """
        Return the modification time of the file storing the session's content.
        """
        modification = os.stat(self._key_to_file()).st_mtime
        if settings.USE_TZ:
            modification = datetime.datetime.utcfromtimestamp(modification)
            modification = modification.replace(tzinfo=timezone.utc)
        else:
            modification = datetime.datetime.fromtimestamp(modification)
        return modification
response.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def set_cookie(self, key, value='', max_age=None, expires=None, path='/',
                   domain=None, secure=False, httponly=False):
        """
        Sets a cookie.

        ``expires`` can be:
        - a string in the correct format,
        - a naive ``datetime.datetime`` object in UTC,
        - an aware ``datetime.datetime`` object in any time zone.
        If it is a ``datetime.datetime`` object then ``max_age`` will be calculated.
        """
        value = force_str(value)
        self.cookies[key] = value
        if expires is not None:
            if isinstance(expires, datetime.datetime):
                if timezone.is_aware(expires):
                    expires = timezone.make_naive(expires, timezone.utc)
                delta = expires - expires.utcnow()
                # Add one second so the date matches exactly (a fraction of
                # time gets lost between converting to a timedelta and
                # then the date string).
                delta = delta + datetime.timedelta(seconds=1)
                # Just set max_age - the max_age logic will set expires.
                expires = None
                max_age = max(0, delta.days * 86400 + delta.seconds)
            else:
                self.cookies[key]['expires'] = expires
        if max_age is not None:
            self.cookies[key]['max-age'] = max_age
            # IE requires expires, so set it if hasn't been already.
            if not expires:
                self.cookies[key]['expires'] = cookie_date(time.time() +
                                                           max_age)
        if path is not None:
            self.cookies[key]['path'] = path
        if domain is not None:
            self.cookies[key]['domain'] = domain
        if secure:
            self.cookies[key]['secure'] = True
        if httponly:
            self.cookies[key]['httponly'] = True
base.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def adapt_datetime_warn_on_aware_datetime(value):
    # Remove this function and rely on the default adapter in Django 2.0.
    if settings.USE_TZ and timezone.is_aware(value):
        warnings.warn(
            "The SQLite database adapter received an aware datetime (%s), "
            "probably from cursor.execute(). Update your code to pass a "
            "naive datetime in the database connection's time zone (UTC by "
            "default).", RemovedInDjango20Warning)
        # This doesn't account for the database connection's timezone,
        # which isn't known. (That's why this adapter is deprecated.)
        value = value.astimezone(timezone.utc).replace(tzinfo=None)
    return value.isoformat(str(" "))
utils.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def typecast_timestamp(s):  # does NOT store time zone information
    # "2005-07-29 15:48:00.590358-05"
    # "2005-07-29 09:56:00-05"
    if not s:
        return None
    if ' ' not in s:
        return typecast_date(s)
    d, t = s.split()
    # Extract timezone information, if it exists. Currently we just throw
    # it away, but in the future we may make use of it.
    if '-' in t:
        t, tz = t.split('-', 1)
        tz = '-' + tz
    elif '+' in t:
        t, tz = t.split('+', 1)
        tz = '+' + tz
    else:
        tz = ''
    dates = d.split('-')
    times = t.split(':')
    seconds = times[2]
    if '.' in seconds:  # check whether seconds have a fractional part
        seconds, microseconds = seconds.split('.')
    else:
        microseconds = '0'
    tzinfo = utc if settings.USE_TZ else None
    return datetime.datetime(int(dates[0]), int(dates[1]), int(dates[2]),
        int(times[0]), int(times[1]), int(seconds),
        int((microseconds + '000000')[:6]), tzinfo)
writer.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def serialize_datetime(value):
        """
        Returns a serialized version of a datetime object that is valid,
        executable python code. It converts timezone-aware values to utc with
        an 'executable' utc representation of tzinfo.
        """
        if value.tzinfo is not None and value.tzinfo != utc:
            value = value.astimezone(utc)
        value_repr = repr(value).replace("<UTC>", "utc")
        if isinstance(value, datetime_safe.datetime):
            value_repr = "datetime.%s" % value_repr
        return value_repr


问题


面经


文章

微信
公众号

扫码关注公众号