Python django.utils.timezone.is_naive() Examples

The following are 30 code examples of django.utils.timezone.is_naive(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.utils.timezone , or try the search function .
Example #1
Source File: utils.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
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 
Example #2
Source File: utils.py    From python2017 with MIT License 6 votes vote down vote up
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 
Example #3
Source File: base.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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. 
Example #4
Source File: models.py    From open-context-py with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #5
Source File: utils.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #6
Source File: utils.py    From bioforum with MIT License 6 votes vote down vote up
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 
Example #7
Source File: base.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
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. 
Example #8
Source File: models.py    From django-modelcluster with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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()) 
Example #9
Source File: date.py    From graphene-django-extras with MIT License 6 votes vote down vote up
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 
Example #10
Source File: util.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #11
Source File: utils.py    From python with Apache License 2.0 6 votes vote down vote up
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 
Example #12
Source File: test_utils.py    From django-rest-framework-simplejwt with MIT License 6 votes vote down vote up
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)) 
Example #13
Source File: pybase.py    From python-ibmdb-django with Apache License 2.0 6 votes vote down vote up
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. 
Example #14
Source File: utils.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
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 
Example #15
Source File: models.py    From open-context-py with GNU General Public License v3.0 5 votes vote down vote up
def save(self, *args, **kwargs):
        """
        saves a manifest item with a good slug
        """
        if self.views is None:
            self.views = 0
        self.label = self.validate_label()
        self.make_slug_and_sort()
        if self.revised is None:
            self.revised = timezone.now()
        elif isinstance(self.revised, datetime):
            if timezone.is_naive(self.revised):
                self.revised = pytz.utc.localize(self.revised)
        if isinstance(self.indexed, datetime):
            if timezone.is_naive(self.indexed):
                self.indexed = pytz.utc.localize(self.indexed)
        if isinstance(self.vcontrol, datetime):
            if timezone.is_naive(self.vcontrol):
                self.vcontrol = pytz.utc.localize(self.vcontrol)
        if isinstance(self.archived, datetime):
            if timezone.is_naive(self.archived):
                self.archived = pytz.utc.localize(self.archived)
        if isinstance(self.published, datetime):
            if timezone.is_naive(self.published):
                self.published = pytz.utc.localize(self.published)
        if isinstance(self.record_updated, datetime):
            if timezone.is_naive(self.record_updated):
                self.record_updated = pytz.utc.localize(self.record_updated)
        super(Manifest, self).save(*args, **kwargs) 
Example #16
Source File: test_utc_date.py    From baobab with GNU General Public License v3.0 5 votes vote down vote up
def test_04_another_tz(self):
        tz = pytz.timezone('US/Hawaii')
        date = datetime.datetime(2014, 5, 9, 18, 00, tzinfo=tz)
        self.assertFalse(is_naive(date))
        api_date = MySerializer().format_datetime(date)
        date = date - tz.utcoffset(date)
        #date = date.astimezone(pytz.UTC)
        self.assertEqual(api_date, date.strftime('%Y-%m-%dT%H:%M:%S+00:00')) 
Example #17
Source File: modelresource.py    From baobab with GNU General Public License v3.0 5 votes vote down vote up
def format_datetime(cls, date):
        if is_naive(date):
            date = pytz.timezone(settings.TIME_ZONE).localize(date)
        if not isinstance(date.tzinfo, pytz.UTC.__class__):
            date = date.astimezone(pytz.UTC)
        # XXX date set in the admin doesn't have microsecond, but the one set
        #     with 'default=now' has, for consistency never output microsecond
        return date.replace(microsecond=0).isoformat() 
Example #18
Source File: test_utc_date.py    From baobab with GNU General Public License v3.0 5 votes vote down vote up
def test_02_default_tz(self):
        tz = pytz.timezone(settings.TIME_ZONE)
        date = datetime.datetime(2014, 5, 9, 18, 00, tzinfo=tz)
        self.assertFalse(is_naive(date))
        api_date = MySerializer().format_datetime(date)
        date = date - tz.utcoffset(date)
        #date = date.astimezone(pytz.UTC)
        self.assertEqual(api_date, date.strftime('%Y-%m-%dT%H:%M:%S+00:00')) 
Example #19
Source File: test_utc_date.py    From baobab with GNU General Public License v3.0 5 votes vote down vote up
def test_01_native_date(self):
        date = datetime.datetime(2014, 5, 9, 18, 00)
        tz = pytz.timezone(settings.TIME_ZONE)
        self.assertTrue(is_naive(date))
        api_date = MySerializer().format_datetime(date)
        date = date - tz.utcoffset(date)
        self.assertEqual(api_date, date.strftime('%Y-%m-%dT%H:%M:%S+00:00')) 
Example #20
Source File: test_utc_date.py    From baobab with GNU General Public License v3.0 5 votes vote down vote up
def test_03_utc_tz(self):
        date = datetime.datetime(2014, 5, 9, 18, 00, tzinfo=pytz.UTC)
        self.assertFalse(is_naive(date))
        api_date = MySerializer().format_datetime(date)
        self.assertEqual(api_date, date.strftime('%Y-%m-%dT%H:%M:%S+00:00')) 
Example #21
Source File: dateformat.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, dt):
        # Accepts either a datetime or date object.
        self.data = dt
        self.timezone = None
        if isinstance(dt, datetime.datetime):
            if is_naive(dt):
                self.timezone = LocalTimezone(dt)
            else:
                self.timezone = dt.tzinfo 
Example #22
Source File: dateformat.py    From python with Apache License 2.0 5 votes vote down vote up
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 
Example #23
Source File: dateformat.py    From python2017 with MIT License 5 votes vote down vote up
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 
Example #24
Source File: test_azure.py    From django-storages with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_get_modified_time_no_tz(self):
        stream = io.BytesIO(b'Im a stream')
        name = self.storage.save('some path/some blob Ϊ.txt', stream)
        self.assertTrue(timezone.is_naive(self.storage.get_modified_time(name))) 
Example #25
Source File: utils.py    From django-rest-framework-simplejwt with MIT License 5 votes vote down vote up
def make_utc(dt):
    if settings.USE_TZ and is_naive(dt):
        return make_aware(dt, timezone=utc)

    return dt 
Example #26
Source File: __init__.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
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 [] 
Example #27
Source File: fields.py    From jbox with MIT License 5 votes vote down vote up
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) 
Example #28
Source File: dateformat.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
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 
Example #29
Source File: test_azure.py    From django-storages with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_modified_time_tz(self):
        stream = io.BytesIO(b'Im a stream')
        name = self.storage.save('some path/some blob Ϊ.txt', stream)
        self.assertTrue(timezone.is_naive(self.storage.modified_time(name))) 
Example #30
Source File: base.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
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