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