python类is_naive()的实例源码

utils.py 文件源码 项目:producthunt 作者: davidgengler 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def from_current_timezone(value):
    """
    When time zone support is enabled, convert naive datetimes
    entered in the current time zone to aware datetimes.
    """
    if settings.USE_TZ and value is not None and timezone.is_naive(value):
        current_timezone = timezone.get_current_timezone()
        try:
            return timezone.make_aware(value, current_timezone)
        except Exception:
            message = _(
                '%(datetime)s couldn\'t be interpreted '
                'in time zone %(current_timezone)s; it '
                'may be ambiguous or it may not exist.'
            )
            params = {'datetime': value, 'current_timezone': current_timezone}
            six.reraise(ValidationError, ValidationError(
                message,
                code='ambiguous_timezone',
                params=params,
            ), sys.exc_info()[2])
    return value
utils.py 文件源码 项目:django-rtc 作者: scifiswapnil 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def from_current_timezone(value):
    """
    When time zone support is enabled, convert naive datetimes
    entered in the current time zone to aware datetimes.
    """
    if settings.USE_TZ and value is not None and timezone.is_naive(value):
        current_timezone = timezone.get_current_timezone()
        try:
            return timezone.make_aware(value, current_timezone)
        except Exception:
            message = _(
                '%(datetime)s couldn\'t be interpreted '
                'in time zone %(current_timezone)s; it '
                'may be ambiguous or it may not exist.'
            )
            params = {'datetime': value, 'current_timezone': current_timezone}
            six.reraise(ValidationError, ValidationError(
                message,
                code='ambiguous_timezone',
                params=params,
            ), sys.exc_info()[2])
    return value
utils.py 文件源码 项目:geekpoint 作者: Lujinghu 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def from_current_timezone(value):
    """
    When time zone support is enabled, convert naive datetimes
    entered in the current time zone to aware datetimes.
    """
    if settings.USE_TZ and value is not None and timezone.is_naive(value):
        current_timezone = timezone.get_current_timezone()
        try:
            return timezone.make_aware(value, current_timezone)
        except Exception:
            message = _(
                '%(datetime)s couldn\'t be interpreted '
                'in time zone %(current_timezone)s; it '
                'may be ambiguous or it may not exist.'
            )
            params = {'datetime': value, 'current_timezone': current_timezone}
            six.reraise(ValidationError, ValidationError(
                message,
                code='ambiguous_timezone',
                params=params,
            ), sys.exc_info()[2])
    return value
utils.py 文件源码 项目:django-next-train 作者: bitpixdigital 项目源码 文件源码 阅读 15 收藏 0 点赞 0 评论 0
def from_current_timezone(value):
    """
    When time zone support is enabled, convert naive datetimes
    entered in the current time zone to aware datetimes.
    """
    if settings.USE_TZ and value is not None and timezone.is_naive(value):
        current_timezone = timezone.get_current_timezone()
        try:
            return timezone.make_aware(value, current_timezone)
        except Exception:
            message = _(
                '%(datetime)s couldn\'t be interpreted '
                'in time zone %(current_timezone)s; it '
                'may be ambiguous or it may not exist.'
            )
            params = {'datetime': value, 'current_timezone': current_timezone}
            six.reraise(ValidationError, ValidationError(
                message,
                code='ambiguous_timezone',
                params=params,
            ), sys.exc_info()[2])
    return value
__init__.py 文件源码 项目:django-next-train 作者: bitpixdigital 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def get_prep_value(self, value):
        value = super(DateTimeField, self).get_prep_value(value)
        value = self.to_python(value)
        if value is not None and settings.USE_TZ and timezone.is_naive(value):
            # For backwards compatibility, interpret naive datetimes in local
            # time. This won't work during DST change, but we can't do much
            # about it, so we let the exceptions percolate up the call stack.
            try:
                name = '%s.%s' % (self.model.__name__, self.name)
            except AttributeError:
                name = '(unbound)'
            warnings.warn("DateTimeField %s received a naive datetime (%s)"
                          " while time zone support is active." %
                          (name, value),
                          RuntimeWarning)
            default_timezone = timezone.get_default_timezone()
            value = timezone.make_aware(value, default_timezone)
        return value
utils.py 文件源码 项目:LatinSounds_AppEnviaMail 作者: G3ek-aR 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def from_current_timezone(value):
    """
    When time zone support is enabled, convert naive datetimes
    entered in the current time zone to aware datetimes.
    """
    if settings.USE_TZ and value is not None and timezone.is_naive(value):
        current_timezone = timezone.get_current_timezone()
        try:
            return timezone.make_aware(value, current_timezone)
        except Exception:
            message = _(
                '%(datetime)s couldn\'t be interpreted '
                'in time zone %(current_timezone)s; it '
                'may be ambiguous or it may not exist.'
            )
            params = {'datetime': value, 'current_timezone': current_timezone}
            six.reraise(ValidationError, ValidationError(
                message,
                code='ambiguous_timezone',
                params=params,
            ), sys.exc_info()[2])
    return value
__init__.py 文件源码 项目:LatinSounds_AppEnviaMail 作者: G3ek-aR 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def get_prep_value(self, value):
        value = super(DateTimeField, self).get_prep_value(value)
        value = self.to_python(value)
        if value is not None and settings.USE_TZ and timezone.is_naive(value):
            # For backwards compatibility, interpret naive datetimes in local
            # time. This won't work during DST change, but we can't do much
            # about it, so we let the exceptions percolate up the call stack.
            try:
                name = '%s.%s' % (self.model.__name__, self.name)
            except AttributeError:
                name = '(unbound)'
            warnings.warn("DateTimeField %s received a naive datetime (%s)"
                          " while time zone support is active." %
                          (name, value),
                          RuntimeWarning)
            default_timezone = timezone.get_default_timezone()
            value = timezone.make_aware(value, default_timezone)
        return value
utils.py 文件源码 项目:DjangoZeroToHero 作者: RayParra 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def from_current_timezone(value):
    """
    When time zone support is enabled, convert naive datetimes
    entered in the current time zone to aware datetimes.
    """
    if settings.USE_TZ and value is not None and timezone.is_naive(value):
        current_timezone = timezone.get_current_timezone()
        try:
            return timezone.make_aware(value, current_timezone)
        except Exception:
            message = _(
                '%(datetime)s couldn\'t be interpreted '
                'in time zone %(current_timezone)s; it '
                'may be ambiguous or it may not exist.'
            )
            params = {'datetime': value, 'current_timezone': current_timezone}
            six.reraise(ValidationError, ValidationError(
                message,
                code='ambiguous_timezone',
                params=params,
            ), sys.exc_info()[2])
    return value
utils.py 文件源码 项目:Roboism 作者: markroxor 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def from_current_timezone(value):
    """
    When time zone support is enabled, convert naive datetimes
    entered in the current time zone to aware datetimes.
    """
    if settings.USE_TZ and value is not None and timezone.is_naive(value):
        current_timezone = timezone.get_current_timezone()
        try:
            return timezone.make_aware(value, current_timezone)
        except Exception:
            message = _(
                '%(datetime)s couldn\'t be interpreted '
                'in time zone %(current_timezone)s; it '
                'may be ambiguous or it may not exist.'
            )
            params = {'datetime': value, 'current_timezone': current_timezone}
            six.reraise(ValidationError, ValidationError(
                message,
                code='ambiguous_timezone',
                params=params,
            ), sys.exc_info()[2])
    return value
utils.py 文件源码 项目:django-wechat-api 作者: crazy-canux 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def from_current_timezone(value):
    """
    When time zone support is enabled, convert naive datetimes
    entered in the current time zone to aware datetimes.
    """
    if settings.USE_TZ and value is not None and timezone.is_naive(value):
        current_timezone = timezone.get_current_timezone()
        try:
            return timezone.make_aware(value, current_timezone)
        except Exception:
            message = _(
                '%(datetime)s couldn\'t be interpreted '
                'in time zone %(current_timezone)s; it '
                'may be ambiguous or it may not exist.'
            )
            params = {'datetime': value, 'current_timezone': current_timezone}
            six.reraise(ValidationError, ValidationError(
                message,
                code='ambiguous_timezone',
                params=params,
            ), sys.exc_info()[2])
    return value
base.py 文件源码 项目:django-wechat-api 作者: crazy-canux 项目源码 文件源码 阅读 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.
__init__.py 文件源码 项目:django-wechat-api 作者: crazy-canux 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def get_prep_value(self, value):
        value = super(DateTimeField, self).get_prep_value(value)
        value = self.to_python(value)
        if value is not None and settings.USE_TZ and timezone.is_naive(value):
            # For backwards compatibility, interpret naive datetimes in local
            # time. This won't work during DST change, but we can't do much
            # about it, so we let the exceptions percolate up the call stack.
            try:
                name = '%s.%s' % (self.model.__name__, self.name)
            except AttributeError:
                name = '(unbound)'
            warnings.warn("DateTimeField %s received a naive datetime (%s)"
                          " while time zone support is active." %
                          (name, value),
                          RuntimeWarning)
            default_timezone = timezone.get_default_timezone()
            value = timezone.make_aware(value, default_timezone)
        return value
util.py 文件源码 项目:django-virtual-pos 作者: intelligenia 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def localize_datetime(_datetime):
    """Localiza la marca de tiempo en función de la zona de tiempo del servidor. Sólo y exclusivamente si no está localizada ya."""
    if timezone.is_naive(_datetime):
        return as_server_datetime(_datetime)
    return _datetime
forms.py 文件源码 项目:tecken 作者: mozilla-services 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _clean_dates(self, values):
        """return a list of either a datetime, date or None.
        Each one can have an operator."""
        if not values:
            return []
        dates = []
        operators = re.compile('<=|>=|<|>|=')
        for block in [x.strip() for x in values.split(',') if x.strip()]:
            if operators.findall(block):
                operator, = operators.findall(block)
            else:
                operator = '='
            rest = operators.sub('', block).strip()
            if rest.lower() in ('null', 'incomplete'):
                date_obj = None
            elif rest.lower() == 'today':
                date_obj = timezone.now().replace(hour=0, minute=0, second=0)
            elif rest.lower() == 'yesterday':
                date_obj = timezone.now().replace(hour=0, minute=0, second=0)
                date_obj -= datetime.timedelta(days=1)
            else:
                try:
                    date_obj = dateutil.parser.parse(rest)
                except ValueError:
                    raise forms.ValidationError(f'Unable to parse {rest!r}')
                if timezone.is_naive(date_obj):
                    date_obj = timezone.make_aware(date_obj)
            dates.append((operator, date_obj))

        return dates
timezone.py 文件源码 项目:zing 作者: evernote 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def test_make_aware(settings):
    """Tests datetimes can be made aware of timezones."""
    settings.USE_TZ = True

    datetime_object = datetime(2016, 1, 2, 21, 52, 25)
    assert timezone.is_naive(datetime_object)
    datetime_aware = make_aware(datetime_object)
    assert timezone.is_aware(datetime_aware)
timezone.py 文件源码 项目:zing 作者: evernote 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def test_make_aware_default_tz(settings):
    """Tests datetimes are made aware of the configured timezone."""
    settings.USE_TZ = True

    datetime_object = datetime(2016, 1, 2, 21, 52, 25)
    assert timezone.is_naive(datetime_object)
    datetime_aware = make_aware(datetime_object)
    assert timezone.is_aware(datetime_aware)

    # Not comparing `tzinfo` directly because that depends on the combination of
    # actual date+times
    assert datetime_aware.tzinfo.zone == timezone.get_default_timezone().zone
timezone.py 文件源码 项目:zing 作者: evernote 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def test_make_aware_explicit_tz(settings):
    """Tests datetimes are made aware of the given timezone."""
    settings.USE_TZ = True

    given_timezone = pytz.timezone('Asia/Bangkok')
    datetime_object = datetime(2016, 1, 2, 21, 52, 25)
    assert timezone.is_naive(datetime_object)
    datetime_aware = make_aware(datetime_object, tz=given_timezone)
    assert timezone.is_aware(datetime_aware)

    assert datetime_aware.tzinfo.zone == given_timezone.zone
timezone.py 文件源码 项目:zing 作者: evernote 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def test_make_aware_use_tz_false(settings):
    """Tests datetimes are left intact if `USE_TZ` is not in effect."""
    settings.USE_TZ = False

    datetime_object = datetime(2016, 1, 2, 21, 52, 25)
    assert timezone.is_naive(datetime_object)
    datetime_aware = make_aware(datetime_object)
    assert timezone.is_naive(datetime_aware)
timezone.py 文件源码 项目:zing 作者: evernote 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_make_naive(settings):
    """Tests datetimes can be made naive of timezones."""
    settings.USE_TZ = True

    datetime_object = datetime(2016, 1, 2, 21, 52, 25, tzinfo=pytz.utc)
    assert timezone.is_aware(datetime_object)
    naive_datetime = make_naive(datetime_object)
    assert timezone.is_naive(naive_datetime)
timezone.py 文件源码 项目:zing 作者: evernote 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def test_make_naive_explicit_tz(settings):
    """Tests datetimes are made naive of the given timezone."""
    settings.USE_TZ = True

    datetime_object = timezone.make_aware(datetime(2016, 1, 2, 21, 52, 25),
                                          timezone=pytz.timezone('Europe/Helsinki'))
    assert timezone.is_aware(datetime_object)
    naive_datetime = make_naive(datetime_object, tz=pytz.timezone('Asia/Bangkok'))
    assert timezone.is_naive(naive_datetime)

    # Conversion from a Helsinki aware datetime to a naive datetime in Bangkok
    # should increment 5 hours (UTC+2 vs. UTC+7)
    assert naive_datetime.hour == (datetime_object.hour + 5) % 24


问题


面经


文章

微信
公众号

扫码关注公众号