當前位置: 首頁>>代碼示例>>Python>>正文


Python timezone.is_naive方法代碼示例

本文整理匯總了Python中django.utils.timezone.is_naive方法的典型用法代碼示例。如果您正苦於以下問題:Python timezone.is_naive方法的具體用法?Python timezone.is_naive怎麽用?Python timezone.is_naive使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在django.utils.timezone的用法示例。


在下文中一共展示了timezone.is_naive方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: from_current_timezone

# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import is_naive [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

示例2: adapt_datetime_with_timezone_support

# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import is_naive [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

示例3: from_current_timezone

# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import is_naive [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

示例4: get_field_value

# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import is_naive [as 別名]
def get_field_value(field, model):
    if field.remote_field is None:
        value = field.pre_save(model, add=model.pk is None)

        # Make datetimes timezone aware
        # https://github.com/django/django/blob/master/django/db/models/fields/__init__.py#L1394-L1403
        if isinstance(value, datetime.datetime) and settings.USE_TZ:
            if timezone.is_naive(value):
                default_timezone = timezone.get_default_timezone()
                value = timezone.make_aware(value, default_timezone).astimezone(timezone.utc)
            # convert to UTC
            value = timezone.localtime(value, timezone.utc)

        if is_protected_type(value):
            return value
        else:
            return field.value_to_string(model)
    else:
        return getattr(model, field.get_attname()) 
開發者ID:wagtail,項目名稱:django-modelcluster,代碼行數:21,代碼來源:models.py

示例5: _parse

# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import is_naive [as 別名]
def _parse(partial_dt):
    """
    parse a partial datetime object to a complete datetime object
    """
    dt = None
    try:
        if isinstance(partial_dt, datetime):
            dt = partial_dt
        if isinstance(partial_dt, date):
            dt = _combine_date_time(partial_dt, time(0, 0, 0))
        if isinstance(partial_dt, time):
            dt = _combine_date_time(date.today(), partial_dt)
        if isinstance(partial_dt, (int, float)):
            dt = datetime.fromtimestamp(partial_dt)
        if isinstance(partial_dt, (str, bytes)):
            dt = parser.parse(partial_dt, default=timezone.now())

        if dt is not None and timezone.is_naive(dt):
            dt = timezone.make_aware(dt)
        return dt
    except ValueError:
        return None 
開發者ID:eamigo86,項目名稱:graphene-django-extras,代碼行數:24,代碼來源:date.py

示例6: _format_parameters

# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import is_naive [as 別名]
def _format_parameters( self, parameters ):
        parameters = list( parameters )
        for index in range( len( parameters ) ):
            # With raw SQL queries, datetimes can reach this function
            # without being converted by DateTimeField.get_db_prep_value.
            if settings.USE_TZ and isinstance( parameters[index], datetime.datetime ):
                param = parameters[index]
                if timezone.is_naive( param ):
                    warnings.warn(u"Received a naive datetime (%s)"
                              u" while time zone support is active." % param,
                              RuntimeWarning)
                    default_timezone = timezone.get_default_timezone()
                    param = timezone.make_aware( param, default_timezone )
                param = param.astimezone(timezone.utc).replace(tzinfo=None)
                parameters[index] = param
        return tuple( parameters )
                
    # Over-riding this method to modify SQLs which contains format parameter to qmark. 
開發者ID:ibmdb,項目名稱:python-ibmdb-django,代碼行數:20,代碼來源:pybase.py

示例7: test_it_should_return_the_correct_values

# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import is_naive [as 別名]
def test_it_should_return_the_correct_values(self):
        # It should make a naive datetime into an aware, utc datetime if django
        # is configured to use timezones and the datetime doesn't already have
        # a timezone

        # Naive datetime
        dt = datetime(year=1970, month=12, day=1)

        with self.settings(USE_TZ=False):
            dt = make_utc(dt)
            self.assertTrue(timezone.is_naive(dt))

        with self.settings(USE_TZ=True):
            dt = make_utc(dt)
            self.assertTrue(timezone.is_aware(dt))
            self.assertEqual(dt.utcoffset(), timedelta(seconds=0)) 
開發者ID:SimpleJWT,項目名稱:django-rest-framework-simplejwt,代碼行數:18,代碼來源:test_utils.py

示例8: from_current_timezone

# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import is_naive [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:
            raise ValidationError(_('%(datetime)s couldn\'t be interpreted '
                                    'in time zone %(current_timezone)s; it '
                                    'may be ambiguous or it may not exist.')
                                  % {'datetime': value,
                                     'current_timezone': current_timezone})
    return value 
開發者ID:blackye,項目名稱:luscan-devel,代碼行數:18,代碼來源:util.py

示例9: adapt_datetime_with_timezone_support

# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import is_naive [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"), 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:blackye,項目名稱:luscan-devel,代碼行數:21,代碼來源:base.py

示例10: save

# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import is_naive [as 別名]
def save(self, *args, **kwargs):
        """
        creates the hash-id on saving to insure a unique assertion
        """
        self.hash_id = self.make_hash_id()
        if self.created is None:
            self.created = timezone.now()
        if self.certainty is None:
            self.certainty = 0
        if isinstance(self.data_date, datetime):
            if timezone.is_naive(self.data_date):
                self.data_date = pytz.utc.localize(self.data_date)
        if isinstance(self.created, datetime):
            if timezone.is_naive(self.created):
                self.created = pytz.utc.localize(self.created)
        if isinstance(self.updated, datetime):
            if timezone.is_naive(self.updated):
                self.updated = pytz.utc.localize(self.updated)
        super(Assertion, self).save(*args, **kwargs) 
開發者ID:ekansa,項目名稱:open-context-py,代碼行數:21,代碼來源:models.py

示例11: process_formdata

# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import is_naive [as 別名]
def process_formdata(self, valuelist):
        super(DateTimeField, self).process_formdata(valuelist)

        date = self.data

        if settings.USE_TZ and date is not None and timezone.is_naive(date):
            current_timezone = timezone.get_current_timezone()
            self.data = timezone.make_aware(date, current_timezone) 
開發者ID:jpush,項目名稱:jbox,代碼行數:10,代碼來源:fields.py

示例12: __init__

# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import is_naive [as 別名]
def __init__(self, obj):
        self.data = obj
        self.timezone = None

        # We only support timezone when formatting datetime objects,
        # not date objects (timezone information not appropriate),
        # or time objects (against established django policy).
        if isinstance(obj, datetime.datetime):
            if is_naive(obj):
                self.timezone = get_default_timezone()
            else:
                self.timezone = obj.tzinfo 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:14,代碼來源:dateformat.py

示例13: parse_datetime_with_timezone_support

# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import is_naive [as 別名]
def parse_datetime_with_timezone_support(value):
    dt = parse_datetime(value)
    # Confirm that dt is naive before overwriting its tzinfo.
    if dt is not None and settings.USE_TZ and timezone.is_naive(dt):
        dt = dt.replace(tzinfo=timezone.utc)
    return dt 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:8,代碼來源:utils.py

示例14: adapt_datetime_with_timezone_support

# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import is_naive [as 別名]
def adapt_datetime_with_timezone_support(value):
    # Equivalent to DateTimeField.get_db_prep_value. Used only by raw SQL.
    if settings.USE_TZ:
        if timezone.is_naive(value):
            warnings.warn("SQLite 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 value.isoformat(str(" ")) 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:13,代碼來源:base.py

示例15: _check_fix_default_value

# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import is_naive [as 別名]
def _check_fix_default_value(self):
        """
        Warn that using an actual date or datetime value is probably wrong;
        it's only evaluated on server startup.
        """
        if not self.has_default():
            return []

        now = timezone.now()
        if not timezone.is_naive(now):
            now = timezone.make_naive(now, timezone.utc)
        value = self.default
        if isinstance(value, datetime.datetime):
            if not timezone.is_naive(value):
                value = timezone.make_naive(value, timezone.utc)
            value = value.date()
        elif isinstance(value, datetime.date):
            # Nothing to do, as dates don't have tz information
            pass
        else:
            # No explicit date / datetime value -- no checks necessary
            return []
        offset = datetime.timedelta(days=1)
        lower = (now - offset).date()
        upper = (now + offset).date()
        if lower <= value <= upper:
            return [
                checks.Warning(
                    'Fixed default value provided.',
                    hint='It seems you set a fixed date / time / datetime '
                         'value as default for this field. This may not be '
                         'what you want. If you want to have the current date '
                         'as default, use `django.utils.timezone.now`',
                    obj=self,
                    id='fields.W161',
                )
            ]

        return [] 
開發者ID:reBiocoder,項目名稱:bioforum,代碼行數:41,代碼來源:__init__.py


注:本文中的django.utils.timezone.is_naive方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。