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


Python settings.USE_TZ属性代码示例

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


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

示例1: datetime

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import USE_TZ [as 别名]
def datetime(self, field=None, val=None):
        """
        Returns a random datetime. If 'val' is passed, a datetime within two
        years of that date will be returned.
        """
        if val is None:
            def source():
                tzinfo = get_default_timezone() if settings.USE_TZ else None
                return datetime.fromtimestamp(randrange(1, 2100000000),
                                              tzinfo)
        else:
            def source():
                tzinfo = get_default_timezone() if settings.USE_TZ else None
                return datetime.fromtimestamp(int(val.strftime("%s")) +
                                              randrange(-365*24*3600*2, 365*24*3600*2),
                                              tzinfo)
        return self.get_allowed_value(source, field) 
开发者ID:BetterWorks,项目名称:django-anonymizer,代码行数:19,代码来源:base.py

示例2: _DATETIME_to_python

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import USE_TZ [as 别名]
def _DATETIME_to_python(self, value, dsc=None):
        """Connector/Python always returns naive datetime.datetime

        Connector/Python always returns naive timestamps since MySQL has
        no time zone support. Since Django needs non-naive, we need to add
        the UTC time zone.

        Returns datetime.datetime()
        """
        if not value:
            return None
        dt = MySQLConverter._DATETIME_to_python(self, value)
        if dt is None:
            return None
        if settings.USE_TZ and timezone.is_naive(dt):
            dt = dt.replace(tzinfo=timezone.utc)
        return dt 
开发者ID:LuciferJack,项目名称:python-mysql-pool,代码行数:19,代码来源:base.py

示例3: datetime_extract_sql

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import USE_TZ [as 别名]
def datetime_extract_sql(self, lookup_type, field_name, tzname):
        # Django 1.6
        if settings.USE_TZ:
            field_name = "CONVERT_TZ({0}, 'UTC', %s)".format(field_name)
            params = [tzname]
        else:
            params = []

        # http://dev.mysql.com/doc/mysql/en/date-and-time-functions.html
        if lookup_type == 'week_day':
            # DAYOFWEEK() returns an integer, 1-7, Sunday=1.
            # Note: WEEKDAY() returns 0-6, Monday=0.
            sql = "DAYOFWEEK({0})".format(field_name)
        else:
            sql = "EXTRACT({0} FROM {1})".format(lookup_type.upper(),
                                                 field_name)
        return sql, params 
开发者ID:LuciferJack,项目名称:python-mysql-pool,代码行数:19,代码来源:operations.py

示例4: datetime_trunc_sql

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import USE_TZ [as 别名]
def datetime_trunc_sql(self, lookup_type, field_name, tzname):
        # Django 1.6
        if settings.USE_TZ:
            field_name = "CONVERT_TZ({0}, 'UTC', %s)".format(field_name)
            params = [tzname]
        else:
            params = []
        fields = ['year', 'month', 'day', 'hour', 'minute', 'second']
        format_ = ('%Y-', '%m', '-%d', ' %H:', '%i', ':%S')
        format_def = ('0000-', '01', '-01', ' 00:', '00', ':00')
        try:
            i = fields.index(lookup_type) + 1
        except ValueError:
            sql = field_name
        else:
            format_str = ''.join([f for f in format_[:i]] +
                                 [f for f in format_def[i:]])
            sql = "CAST(DATE_FORMAT({0}, '{1}') AS DATETIME)".format(
                field_name, format_str)
        return sql, params 
开发者ID:LuciferJack,项目名称:python-mysql-pool,代码行数:22,代码来源:operations.py

示例5: from_current_timezone

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import USE_TZ [as 别名]
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 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:24,代码来源:utils.py

示例6: template_localtime

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import USE_TZ [as 别名]
def template_localtime(value, use_tz=None):
    """
    Checks if value is a datetime and converts it to local time if necessary.

    If use_tz is provided and is not None, that will force the value to
    be converted (or not), overriding the value of settings.USE_TZ.

    This function is designed for use by the template engine.
    """
    should_convert = (isinstance(value, datetime)
        and (settings.USE_TZ if use_tz is None else use_tz)
        and not is_naive(value)
        and getattr(value, 'convert_to_local_time', True))
    return localtime(value) if should_convert else value


# Utilities 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:19,代码来源:timezone.py

示例7: ensure_defaults

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import USE_TZ [as 别名]
def ensure_defaults(self, alias):
        """
        Puts the defaults into the settings dictionary for a given connection
        where no settings is provided.
        """
        try:
            conn = self.databases[alias]
        except KeyError:
            raise ConnectionDoesNotExist("The connection %s doesn't exist" % alias)

        conn.setdefault('ATOMIC_REQUESTS', False)
        conn.setdefault('AUTOCOMMIT', True)
        conn.setdefault('ENGINE', 'django.db.backends.dummy')
        if conn['ENGINE'] == 'django.db.backends.' or not conn['ENGINE']:
            conn['ENGINE'] = 'django.db.backends.dummy'
        conn.setdefault('CONN_MAX_AGE', 0)
        conn.setdefault('OPTIONS', {})
        conn.setdefault('TIME_ZONE', 'UTC' if settings.USE_TZ else settings.TIME_ZONE)
        for setting in ['NAME', 'USER', 'PASSWORD', 'HOST', 'PORT']:
            conn.setdefault(setting, '') 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:22,代码来源:utils.py

示例8: adapt_datetime_with_timezone_support

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import USE_TZ [as 别名]
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. 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:21,代码来源:base.py

示例9: datetime_trunc_sql

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import USE_TZ [as 别名]
def datetime_trunc_sql(self, lookup_type, field_name, tzname):
        if settings.USE_TZ:
            field_name = "CONVERT_TZ(%s, 'UTC', %%s)" % field_name
            params = [tzname]
        else:
            params = []
        fields = ['year', 'month', 'day', 'hour', 'minute', 'second']
        format = ('%%Y-', '%%m', '-%%d', ' %%H:', '%%i', ':%%s')  # Use double percents to escape.
        format_def = ('0000-', '01', '-01', ' 00:', '00', ':00')
        try:
            i = fields.index(lookup_type) + 1
        except ValueError:
            sql = field_name
        else:
            format_str = ''.join([f for f in format[:i]] + [f for f in format_def[i:]])
            sql = "CAST(DATE_FORMAT(%s, '%s') AS DATETIME)" % (field_name, format_str)
        return sql, params 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:19,代码来源:operations.py

示例10: datetimes

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import USE_TZ [as 别名]
def datetimes(self, field_name, kind, order='ASC', tzinfo=None):
        """
        Returns a list of datetime objects representing all available
        datetimes for the given field_name, scoped to 'kind'.
        """
        assert kind in ("year", "month", "day", "hour", "minute", "second"), \
            "'kind' must be one of 'year', 'month', 'day', 'hour', 'minute' or 'second'."
        assert order in ('ASC', 'DESC'), \
            "'order' must be either 'ASC' or 'DESC'."
        if settings.USE_TZ:
            if tzinfo is None:
                tzinfo = timezone.get_current_timezone()
        else:
            tzinfo = None
        return self.annotate(
            datetimefield=DateTime(field_name, kind, tzinfo),
            plain_field=F(field_name)
        ).values_list(
            'datetimefield', flat=True
        ).distinct().filter(plain_field__isnull=False).order_by(('-' if order == 'DESC' else '') + 'datetimefield') 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:22,代码来源:query.py

示例11: get_prep_value

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import USE_TZ [as 别名]
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 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:20,代码来源:__init__.py

示例12: _cull

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import USE_TZ [as 别名]
def _cull(self, db, cursor, now):
        if self._cull_frequency == 0:
            self.clear()
        else:
            # When USE_TZ is True, 'now' will be an aware datetime in UTC.
            now = now.replace(tzinfo=None)
            table = connections[db].ops.quote_name(self._table)
            cursor.execute("DELETE FROM %s WHERE expires < %%s" % table,
                           [connections[db].ops.value_to_db_datetime(now)])
            cursor.execute("SELECT COUNT(*) FROM %s" % table)
            num = cursor.fetchone()[0]
            if num > self._max_entries:
                cull_num = num // self._cull_frequency
                cursor.execute(
                    connections[db].ops.cache_key_culling_sql() % table,
                    [cull_num])
                cursor.execute("DELETE FROM %s "
                               "WHERE cache_key < %%s" % table,
                               [cursor.fetchone()[0]]) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:21,代码来源:db.py

示例13: parse_date_input

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import USE_TZ [as 别名]
def parse_date_input(value):
    """Return datetime based on the user's input.

    @param value: User's input
    @type value: str
    @raise ValueError: If the input is not valid.
    @return: Datetime of the beginning of the user's date.
    """
    try:
        limit = parse_date(value)
    except ValueError:
        limit = None
    if limit is None:
        raise ValueError("'{}' is not a valid date.".format(value))
    limit = datetime(limit.year, limit.month, limit.day)
    if settings.USE_TZ:
        limit = make_aware(limit)
    return limit 
开发者ID:adamalton,项目名称:django-csp-reports,代码行数:20,代码来源:utils.py

示例14: __init__

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import USE_TZ [as 别名]
def __init__(self, environment):
        super(DjangoL10n, self).__init__(environment)
        finalize = []
        if settings.USE_TZ:
            finalize.append(template_localtime)
        if settings.USE_L10N:
            finalize.append(localize)

        if finalize:
            fns = iter(finalize)
            if environment.finalize is None:
                new_finalize = next(fns)
            else:
                new_finalize = environment.finalize
            for f in fns:
                new_finalize = self._compose(f, new_finalize)

            environment.finalize = new_finalize 
开发者ID:MoritzS,项目名称:jinja2-django-tags,代码行数:20,代码来源:extensions.py

示例15: from_current_timezone

# 需要导入模块: from django.conf import settings [as 别名]
# 或者: from django.conf.settings import USE_TZ [as 别名]
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 as exc:
            raise ValidationError(
                _('%(datetime)s couldn\'t be interpreted '
                  'in time zone %(current_timezone)s; it '
                  'may be ambiguous or it may not exist.'),
                code='ambiguous_timezone',
                params={'datetime': value, 'current_timezone': current_timezone}
            ) from exc
    return value 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:20,代码来源:utils.py


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