当前位置: 首页>>代码示例>>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;未经允许,请勿转载。