Python django.utils.timezone.make_naive() Examples

The following are 30 code examples of django.utils.timezone.make_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: operations.py    From python2017 with MIT License 6 votes vote down vote up
def adapt_datetimefield_value(self, value):
        """
        Transform a datetime value to an object compatible with what is expected
        by the backend driver for datetime columns.

        If naive datetime is passed assumes that is in UTC. Normally Django
        models.DateTimeField makes sure that if USE_TZ is True passed datetime
        is timezone aware.
        """

        if value is None:
            return None

        # Expression values are adapted by the database.
        if hasattr(value, 'resolve_expression'):
            return value

        # cx_Oracle doesn't support tz-aware datetimes
        if timezone.is_aware(value):
            if settings.USE_TZ:
                value = timezone.make_naive(value, self.connection.timezone)
            else:
                raise ValueError("Oracle backend does not support timezone-aware datetimes when USE_TZ is False.")

        return Oracle_datetime.from_datetime(value) 
Example #2
Source File: operations.py    From python with Apache License 2.0 6 votes vote down vote up
def adapt_datetimefield_value(self, value):
        if value is None:
            return None

        # Expression values are adapted by the database.
        if hasattr(value, 'resolve_expression'):
            return value

        # SQLite doesn't support tz-aware datetimes
        if timezone.is_aware(value):
            if settings.USE_TZ:
                value = timezone.make_naive(value, self.connection.timezone)
            else:
                raise ValueError("SQLite backend does not support timezone-aware datetimes when USE_TZ is False.")

        return six.text_type(value) 
Example #3
Source File: operations.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def adapt_datetimefield_value(self, value):
        """
        Transform a datetime value to an object compatible with what is expected
        by the backend driver for datetime columns.

        If naive datetime is passed assumes that is in UTC. Normally Django
        models.DateTimeField makes sure that if USE_TZ is True passed datetime
        is timezone aware.
        """

        if value is None:
            return None

        # Expression values are adapted by the database.
        if hasattr(value, 'resolve_expression'):
            return value

        # cx_Oracle doesn't support tz-aware datetimes
        if timezone.is_aware(value):
            if settings.USE_TZ:
                value = timezone.make_naive(value, self.connection.timezone)
            else:
                raise ValueError("Oracle backend does not support timezone-aware datetimes when USE_TZ is False.")

        return Oracle_datetime.from_datetime(value) 
Example #4
Source File: operations.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def adapt_datetimefield_value(self, value):
        if value is None:
            return None

        # Expression values are adapted by the database.
        if hasattr(value, 'resolve_expression'):
            return value

        # SQLite doesn't support tz-aware datetimes
        if timezone.is_aware(value):
            if settings.USE_TZ:
                value = timezone.make_naive(value, self.connection.timezone)
            else:
                raise ValueError("SQLite backend does not support timezone-aware datetimes when USE_TZ is False.")

        return str(value) 
Example #5
Source File: operations.py    From python with Apache License 2.0 6 votes vote down vote up
def adapt_datetimefield_value(self, value):
        """
        Transform a datetime value to an object compatible with what is expected
        by the backend driver for datetime columns.

        If naive datetime is passed assumes that is in UTC. Normally Django
        models.DateTimeField makes sure that if USE_TZ is True passed datetime
        is timezone aware.
        """

        if value is None:
            return None

        # Expression values are adapted by the database.
        if hasattr(value, 'resolve_expression'):
            return value

        # cx_Oracle doesn't support tz-aware datetimes
        if timezone.is_aware(value):
            if settings.USE_TZ:
                value = timezone.make_naive(value, self.connection.timezone)
            else:
                raise ValueError("Oracle backend does not support timezone-aware datetimes when USE_TZ is False.")

        return Oracle_datetime.from_datetime(value) 
Example #6
Source File: operations.py    From python with Apache License 2.0 6 votes vote down vote up
def adapt_datetimefield_value(self, value):
        if value is None:
            return None

        # Expression values are adapted by the database.
        if hasattr(value, 'resolve_expression'):
            return value

        # MySQL doesn't support tz-aware datetimes
        if timezone.is_aware(value):
            if settings.USE_TZ:
                value = timezone.make_naive(value, self.connection.timezone)
            else:
                raise ValueError("MySQL backend does not support timezone-aware datetimes when USE_TZ is False.")

        if not self.connection.features.supports_microsecond_precision:
            value = value.replace(microsecond=0)

        return six.text_type(value) 
Example #7
Source File: operations.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def adapt_datetimefield_value(self, value):
        """
        Transform a datetime value to an object compatible with what is expected
        by the backend driver for datetime columns.

        If naive datetime is passed assumes that is in UTC. Normally Django
        models.DateTimeField makes sure that if USE_TZ is True passed datetime
        is timezone aware.
        """

        if value is None:
            return None

        # cx_Oracle doesn't support tz-aware datetimes
        if timezone.is_aware(value):
            if settings.USE_TZ:
                value = timezone.make_naive(value, self.connection.timezone)
            else:
                raise ValueError("Oracle backend does not support timezone-aware datetimes when USE_TZ is False.")

        return Oracle_datetime.from_datetime(value) 
Example #8
Source File: mt_models.py    From zentral with Apache License 2.0 6 votes vote down vote up
def add_field(self, k, v):
        if not isinstance(k, str) or not k:
            raise ValueError("Invalid field name {}".format(k))
        if k in self.fields:
            raise ValueError("Field {} already added".format(k))
        if self.is_empty_value(v):
            return
        elif isinstance(v, int):
            v = str(v)
        elif isinstance(v, datetime):
            if is_aware(v):
                v = make_naive(v)
            v = v.isoformat()
        elif isinstance(v, list):
            assert(all([isinstance(e, str) and len(e) == 40 for e in v]))
        elif not isinstance(v, str):
            raise ValueError("Invalid field value {} for field {}".format(v, k))
        self.fields[k] = v 
Example #9
Source File: trackers.py    From django-trackstats with MIT License 6 votes vote down vote up
def get_start_date(self, qs):
        most_recent_kwargs = self.get_most_recent_kwargs()
        last_stat = self.statistic_model.objects.most_recent(
            **most_recent_kwargs)
        if last_stat:
            start_date = last_stat.date
        else:
            first_instance = qs.order_by(self.date_field).first()
            if first_instance is None:
                # No data
                return
            start_date = getattr(first_instance, self.date_field)
        if start_date and isinstance(start_date, datetime):
            if timezone.is_aware(start_date):
                start_date = timezone.make_naive(start_date).date()
            else:
                start_date = start_date.date()
        return start_date 
Example #10
Source File: 0022_localize_datetimes.py    From GetTogether with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def localize_event_datetimes(apps, schema_editor):
    Event = MyModel = apps.get_model("events", "Event")
    for event in Event.objects.all():
        utc_tz = pytz.timezone("UTC")
        event_tz = get_event_timezone(event)
        print("Converting event %s to %s" % (event.id, event_tz))
        event.start_time = utc_tz.localize(
            timezone.make_naive(
                event_tz.localize(timezone.make_naive(event.start_time, pytz.utc))
            )
        )
        event.end_time = utc_tz.localize(
            timezone.make_naive(
                event_tz.localize(timezone.make_naive(event.end_time, pytz.utc))
            )
        )
        event.save() 
Example #11
Source File: operations.py    From python2017 with MIT License 6 votes vote down vote up
def adapt_datetimefield_value(self, value):
        if value is None:
            return None

        # Expression values are adapted by the database.
        if hasattr(value, 'resolve_expression'):
            return value

        # SQLite doesn't support tz-aware datetimes
        if timezone.is_aware(value):
            if settings.USE_TZ:
                value = timezone.make_naive(value, self.connection.timezone)
            else:
                raise ValueError("SQLite backend does not support timezone-aware datetimes when USE_TZ is False.")

        return six.text_type(value) 
Example #12
Source File: operations.py    From python2017 with MIT License 6 votes vote down vote up
def adapt_datetimefield_value(self, value):
        if value is None:
            return None

        # Expression values are adapted by the database.
        if hasattr(value, 'resolve_expression'):
            return value

        # MySQL doesn't support tz-aware datetimes
        if timezone.is_aware(value):
            if settings.USE_TZ:
                value = timezone.make_naive(value, self.connection.timezone)
            else:
                raise ValueError("MySQL backend does not support timezone-aware datetimes when USE_TZ is False.")

        if not self.connection.features.supports_microsecond_precision:
            value = value.replace(microsecond=0)

        return six.text_type(value) 
Example #13
Source File: operations.py    From bioforum with MIT License 6 votes vote down vote up
def adapt_datetimefield_value(self, value):
        if value is None:
            return None

        # Expression values are adapted by the database.
        if hasattr(value, 'resolve_expression'):
            return value

        # MySQL doesn't support tz-aware datetimes
        if timezone.is_aware(value):
            if settings.USE_TZ:
                value = timezone.make_naive(value, self.connection.timezone)
            else:
                raise ValueError("MySQL backend does not support timezone-aware datetimes when USE_TZ is False.")

        if not self.connection.features.supports_microsecond_precision:
            value = value.replace(microsecond=0)

        return str(value) 
Example #14
Source File: operations.py    From bioforum with MIT License 6 votes vote down vote up
def adapt_datetimefield_value(self, value):
        """
        Transform a datetime value to an object compatible with what is expected
        by the backend driver for datetime columns.

        If naive datetime is passed assumes that is in UTC. Normally Django
        models.DateTimeField makes sure that if USE_TZ is True passed datetime
        is timezone aware.
        """

        if value is None:
            return None

        # Expression values are adapted by the database.
        if hasattr(value, 'resolve_expression'):
            return value

        # cx_Oracle doesn't support tz-aware datetimes
        if timezone.is_aware(value):
            if settings.USE_TZ:
                value = timezone.make_naive(value, self.connection.timezone)
            else:
                raise ValueError("Oracle backend does not support timezone-aware datetimes when USE_TZ is False.")

        return Oracle_datetime.from_datetime(value) 
Example #15
Source File: operations.py    From bioforum with MIT License 6 votes vote down vote up
def adapt_datetimefield_value(self, value):
        if value is None:
            return None

        # Expression values are adapted by the database.
        if hasattr(value, 'resolve_expression'):
            return value

        # SQLite doesn't support tz-aware datetimes
        if timezone.is_aware(value):
            if settings.USE_TZ:
                value = timezone.make_naive(value, self.connection.timezone)
            else:
                raise ValueError("SQLite backend does not support timezone-aware datetimes when USE_TZ is False.")

        return str(value) 
Example #16
Source File: 0022_localize_datetimes.py    From GetTogether with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def localize_commonevent_datetimes(apps, schema_editor):
    CommonEvent = MyModel = apps.get_model("events", "CommonEvent")
    for event in CommonEvent.objects.all():
        utc_tz = pytz.timezone("UTC")
        event_tz = get_event_timezone(event)
        print("Converting common event %s to %s" % (event.id, event_tz))
        event.start_time = utc_tz.localize(
            timezone.make_naive(
                event_tz.localize(timezone.make_naive(event.start_time, pytz.utc))
            )
        )
        event.end_time = utc_tz.localize(
            timezone.make_naive(
                event_tz.localize(timezone.make_naive(event.end_time, pytz.utc))
            )
        )
        event.save() 
Example #17
Source File: __init__.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def to_python(self, value):
        if value is None:
            return value
        if isinstance(value, datetime.datetime):
            if settings.USE_TZ and timezone.is_aware(value):
                # Convert aware datetimes to the default time zone
                # before casting them to dates (#17742).
                default_timezone = timezone.get_default_timezone()
                value = timezone.make_naive(value, default_timezone)
            return value.date()
        if isinstance(value, datetime.date):
            return value

        try:
            parsed = parse_date(value)
            if parsed is not None:
                return parsed
        except ValueError:
            msg = self.error_messages['invalid_date'] % value
            raise exceptions.ValidationError(msg)

        msg = self.error_messages['invalid'] % value
        raise exceptions.ValidationError(msg) 
Example #18
Source File: test_gcloud.py    From django-storages with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_get_modified_time(self):
        naive_date = datetime(2017, 1, 2, 3, 4, 5, 678)
        aware_date = timezone.make_aware(naive_date, timezone.utc)

        self.storage._bucket = mock.MagicMock()
        blob = mock.MagicMock()
        blob.updated = aware_date
        self.storage._bucket.get_blob.return_value = blob

        with self.settings(TIME_ZONE='America/Montreal', USE_TZ=False):
            mt = self.storage.get_modified_time(self.filename)
            self.assertTrue(timezone.is_naive(mt))
            naive_date_montreal = timezone.make_naive(aware_date)
            self.assertEqual(mt, naive_date_montreal)
            self.storage._bucket.get_blob.assert_called_with(self.filename)

        with self.settings(TIME_ZONE='America/Montreal', USE_TZ=True):
            mt = self.storage.get_modified_time(self.filename)
            self.assertTrue(timezone.is_aware(mt))
            self.assertEqual(mt, aware_date)
            self.storage._bucket.get_blob.assert_called_with(self.filename) 
Example #19
Source File: test_gcloud.py    From django-storages with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_get_created_time(self):
        naive_date = datetime(2017, 1, 2, 3, 4, 5, 678)
        aware_date = timezone.make_aware(naive_date, timezone.utc)

        self.storage._bucket = mock.MagicMock()
        blob = mock.MagicMock()
        blob.time_created = aware_date
        self.storage._bucket.get_blob.return_value = blob

        with self.settings(TIME_ZONE='America/Montreal', USE_TZ=False):
            mt = self.storage.get_created_time(self.filename)
            self.assertTrue(timezone.is_naive(mt))
            naive_date_montreal = timezone.make_naive(aware_date)
            self.assertEqual(mt, naive_date_montreal)
            self.storage._bucket.get_blob.assert_called_with(self.filename)

        with self.settings(TIME_ZONE='America/Montreal', USE_TZ=True):
            mt = self.storage.get_created_time(self.filename)
            self.assertTrue(timezone.is_aware(mt))
            self.assertEqual(mt, aware_date)
            self.storage._bucket.get_blob.assert_called_with(self.filename) 
Example #20
Source File: forms.py    From GetTogether with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def clean(self):
        cleaned_data = super().clean()
        event_tz = pytz.timezone(self.instance.tz)
        cleaned_data["start_time"] = pytz.utc.localize(
            timezone.make_naive(
                event_tz.localize(timezone.make_naive(cleaned_data["start_time"]))
            )
        )
        cleaned_data["end_time"] = pytz.utc.localize(
            timezone.make_naive(
                event_tz.localize(timezone.make_naive(cleaned_data["end_time"]))
            )
        )
        return cleaned_data 
Example #21
Source File: response.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def set_cookie(self, key, value='', max_age=None, expires=None, path='/',
                   domain=None, secure=False, httponly=False):
        """
        Sets a cookie.

        ``expires`` can be:
        - a string in the correct format,
        - a naive ``datetime.datetime`` object in UTC,
        - an aware ``datetime.datetime`` object in any time zone.
        If it is a ``datetime.datetime`` object then ``max_age`` will be calculated.

        """
        self.cookies[key] = value
        if expires is not None:
            if isinstance(expires, datetime.datetime):
                if timezone.is_aware(expires):
                    expires = timezone.make_naive(expires, timezone.utc)
                delta = expires - expires.utcnow()
                # Add one second so the date matches exactly (a fraction of
                # time gets lost between converting to a timedelta and
                # then the date string).
                delta = delta + datetime.timedelta(seconds=1)
                # Just set max_age - the max_age logic will set expires.
                expires = None
                max_age = max(0, delta.days * 86400 + delta.seconds)
            else:
                self.cookies[key]['expires'] = expires
        if max_age is not None:
            self.cookies[key]['max-age'] = max_age
            # IE requires expires, so set it if hasn't been already.
            if not expires:
                self.cookies[key]['expires'] = cookie_date(time.time() +
                                                           max_age)
        if path is not None:
            self.cookies[key]['path'] = path
        if domain is not None:
            self.cookies[key]['domain'] = domain
        if secure:
            self.cookies[key]['secure'] = True
        if httponly:
            self.cookies[key]['httponly'] = True 
Example #22
Source File: utils.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def to_current_timezone(value):
    """
    When time zone support is enabled, convert aware datetimes
    to naive datetimes in the current time zone for display.
    """
    if settings.USE_TZ and value is not None and timezone.is_aware(value):
        current_timezone = timezone.get_current_timezone()
        return timezone.make_naive(value, current_timezone)
    return value 
Example #23
Source File: changeset.py    From c3nav with Apache License 2.0 5 votes vote down vote up
def last_change_cache_key(self):
        last_change = self.created if self.last_change_id is None else self.last_change.datetime
        return int_to_base36(self.last_change_id or 0)+'_'+int_to_base36(int(make_naive(last_change).timestamp())) 
Example #24
Source File: util.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def to_current_timezone(value):
    """
    When time zone support is enabled, convert aware datetimes
    to naive dateimes in the current time zone for display.
    """
    if settings.USE_TZ and value is not None and timezone.is_aware(value):
        current_timezone = timezone.get_current_timezone()
        return timezone.make_naive(value, current_timezone)
    return value 
Example #25
Source File: test_timezone.py    From django-peeringdb with Apache License 2.0 5 votes vote down vote up
def test_conversion(self):
        input = "2020-02-04T20:34:14Z"
        parsed = parse_datetime(input)

        assert parsed.year == 2020
        assert parsed.month == 2
        assert parsed.day == 4
        assert parsed.hour == 20
        assert parsed.minute == 34
        assert parsed.utcoffset().seconds == 0

        stripped = parsed.replace(tzinfo=None)

        assert stripped.year == 2020
        assert stripped.month == 2
        assert stripped.day == 4
        assert stripped.hour == 20
        assert stripped.minute == 34
        assert stripped.utcoffset() is None

        aware = make_aware(stripped)

        assert aware.year == 2020
        assert aware.month == 2
        assert aware.day == 4
        assert aware.hour == 20
        assert aware.minute == 34
        assert aware.utcoffset().seconds == 0

        naive = make_naive(aware, timezone=utc)

        assert naive.year == 2020
        assert naive.month == 2
        assert naive.day == 4
        assert naive.hour == 20
        assert naive.minute == 34
        assert naive.utcoffset() is None 
Example #26
Source File: forms.py    From GetTogether with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def clean(self):
        cleaned_data = super().clean()
        event_tz = pytz.timezone(self.instance.tz)
        cleaned_data["start_time"] = pytz.utc.localize(
            timezone.make_naive(
                event_tz.localize(timezone.make_naive(cleaned_data["start_time"]))
            )
        )
        cleaned_data["end_time"] = pytz.utc.localize(
            timezone.make_naive(
                event_tz.localize(timezone.make_naive(cleaned_data["end_time"]))
            )
        )
        return cleaned_data 
Example #27
Source File: models.py    From django-ca with GNU General Public License v3.0 5 votes vote down vote up
def get_compromised_time(self):
        if self.revoked is False or not self.compromised:
            return

        if timezone.is_aware(self.compromised):
            # convert datetime object to UTC and make it naive
            return timezone.make_naive(self.compromised, pytz.utc)

        return self.compromised 
Example #28
Source File: events.py    From GetTogether with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def create_next_in_series(self):
        next_date = self.recurrences.after(self.last_time, dtstart=self.last_time)
        if next_date is None:
            return None
        event_tz = pytz.timezone(self.tz)

        next_start = pytz.utc.localize(
            timezone.make_naive(
                event_tz.localize(
                    datetime.datetime.combine(next_date.date(), self.start_time)
                )
            )
        )
        next_end = pytz.utc.localize(
            timezone.make_naive(
                event_tz.localize(
                    datetime.datetime.combine(next_date.date(), self.end_time)
                )
            )
        )
        next_event = Event(
            series=self,
            team=self.team,
            name=self.name,
            start_time=next_start,
            end_time=next_end,
            summary=self.summary,
            place=self.place,
            created_by=self.created_by,
            attendee_limit=self.attendee_limit,
        )
        next_event.save()
        Attendee.objects.create(
            event=next_event,
            user=self.created_by,
            role=Attendee.HOST,
            status=Attendee.YES,
        )
        self.last_time = next_event.start_time
        self.save()
        return next_event 
Example #29
Source File: events.py    From GetTogether with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def local_end_time(self, val=None):
        if val is not None:
            self.end_time = val.astimezone(python.utc)
        else:
            if self.end_time is None:
                return None
            event_tz = pytz.timezone(self.tz)
            return timezone.make_naive(self.end_time.astimezone(event_tz), event_tz) 
Example #30
Source File: events.py    From GetTogether with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def local_start_time(self, val=None):
        if val is not None:
            self.start_time = val.astimezone(python.utc)
        else:
            if self.start_time is None:
                return None
            event_tz = pytz.timezone(self.tz)
            return timezone.make_naive(self.start_time.astimezone(event_tz), event_tz)