Python django.utils.timezone.make_aware() Examples

The following are 30 code examples for showing how to use django.utils.timezone.make_aware(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.utils.timezone , or try the search function .

Example 1
Project: GTDWeb   Author: lanbing510   File: utils.py    License: 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 2
Project: GTDWeb   Author: lanbing510   File: base.py    License: 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 3
Project: GTDWeb   Author: lanbing510   File: __init__.py    License: GNU General Public License v2.0 6 votes vote down vote up
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 
Example 4
Project: django-csp-reports   Author: adamalton   File: utils.py    License: MIT License 6 votes vote down vote up
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 
Example 5
Project: kobo-predict   Author: awemulya   File: sync_deleted_instances_fix.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def handle(self, *args, **kwargs):
        # Reset all sql deletes to None
        Instance.objects.exclude(
            deleted_at=None, xform__downloadable=True).update(deleted_at=None)

        # Get all mongo deletes
        query = '{"$and": [{"_deleted_at": {"$exists": true}}, ' \
                '{"_deleted_at": {"$ne": null}}]}'
        query = json.loads(query)
        xform_instances = settings.MONGO_DB.instances
        cursor = xform_instances.find(query)
        for record in cursor:
            # update sql instance with deleted_at datetime from mongo
            try:
                i = Instance.objects.get(
                    uuid=record["_uuid"],  xform__downloadable=True)
            except Instance.DoesNotExist:
                continue
            else:
                deleted_at = parse_datetime(record["_deleted_at"])
                if not timezone.is_aware(deleted_at):
                    deleted_at = timezone.make_aware(
                        deleted_at, timezone.utc)
                i.set_deleted(deleted_at) 
Example 6
Project: bioforum   Author: reBiocoder   File: utils.py    License: 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
Project: bioforum   Author: reBiocoder   File: operations.py    License: MIT License 6 votes vote down vote up
def year_lookup_bounds_for_datetime_field(self, value):
        """
        Return a two-elements list with the lower and upper bound to be used
        with a BETWEEN operator to query a DateTimeField value using a year
        lookup.

        `value` is an int, containing the looked-up year.
        """
        first = datetime.datetime(value, 1, 1)
        second = datetime.datetime(value, 12, 31, 23, 59, 59, 999999)
        if settings.USE_TZ:
            tz = timezone.get_current_timezone()
            first = timezone.make_aware(first, tz)
            second = timezone.make_aware(second, tz)
        first = self.adapt_datetimefield_value(first)
        second = self.adapt_datetimefield_value(second)
        return [first, second] 
Example 8
Project: bioforum   Author: reBiocoder   File: datetime.py    License: MIT License 6 votes vote down vote up
def convert_value(self, value, expression, connection):
        if isinstance(self.output_field, DateTimeField):
            if settings.USE_TZ:
                if value is None:
                    raise ValueError(
                        "Database returned an invalid datetime value. "
                        "Are time zone definitions for your database installed?"
                    )
                value = value.replace(tzinfo=None)
                value = timezone.make_aware(value, self.tzinfo)
        elif isinstance(value, datetime):
            if isinstance(self.output_field, DateField):
                value = value.date()
            elif isinstance(self.output_field, TimeField):
                value = value.time()
        return value 
Example 9
Project: bioforum   Author: reBiocoder   File: __init__.py    License: MIT License 6 votes vote down vote up
def get_prep_value(self, value):
        value = super().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 
Example 10
Project: pycon   Author: pythonitalia   File: test_models.py    License: MIT License 6 votes vote down vote up
def test_conference_cannot_have_two_deadlines_of_type_event(deadline_factory):
    deadline1 = deadline_factory(
        type="event",
        start=timezone.make_aware(datetime(2018, 5, 5)),
        end=timezone.make_aware(datetime(2018, 6, 3)),
    )

    deadline1.clean()

    deadline2 = deadline_factory(
        type="event",
        conference=deadline1.conference,
        start=timezone.make_aware(datetime(2018, 6, 5)),
        end=timezone.make_aware(datetime(2018, 10, 4)),
    )

    with raises(exceptions.ValidationError) as e:
        deadline2.clean()

    assert "You can only have one deadline of type event" in str(e.value) 
Example 11
Project: pycon   Author: pythonitalia   File: test_models.py    License: MIT License 6 votes vote down vote up
def test_conference_cannot_have_two_deadlines_of_type_cfp(deadline_factory):
    deadline1 = deadline_factory(
        type="cfp",
        start=timezone.make_aware(datetime(2018, 5, 5)),
        end=timezone.make_aware(datetime(2018, 6, 3)),
    )

    deadline1.clean()

    deadline2 = deadline_factory(
        type="cfp",
        conference=deadline1.conference,
        start=timezone.make_aware(datetime(2018, 6, 5)),
        end=timezone.make_aware(datetime(2018, 10, 4)),
    )

    with raises(exceptions.ValidationError) as e:
        deadline2.clean()

    assert "You can only have one deadline of type cfp" in str(e.value) 
Example 12
Project: pycon   Author: pythonitalia   File: test_models.py    License: MIT License 6 votes vote down vote up
def test_conference_cannot_have_two_deadlines_of_type_voting(deadline_factory):
    deadline1 = deadline_factory(
        type="voting",
        start=timezone.make_aware(datetime(2018, 5, 5)),
        end=timezone.make_aware(datetime(2018, 6, 3)),
    )

    deadline1.clean()

    deadline2 = deadline_factory(
        type="voting",
        conference=deadline1.conference,
        start=timezone.make_aware(datetime(2018, 6, 5)),
        end=timezone.make_aware(datetime(2018, 10, 4)),
    )

    with raises(exceptions.ValidationError) as e:
        deadline2.clean()

    assert "You can only have one deadline of type voting" in str(e.value) 
Example 13
Project: pycon   Author: pythonitalia   File: test_models.py    License: MIT License 6 votes vote down vote up
def test_conference_cannot_have_two_deadlines_of_type_refund(deadline_factory):
    deadline1 = deadline_factory(
        type="refund",
        start=timezone.make_aware(datetime(2018, 5, 5)),
        end=timezone.make_aware(datetime(2018, 6, 3)),
    )

    deadline1.clean()

    deadline2 = deadline_factory(
        type="refund",
        conference=deadline1.conference,
        start=timezone.make_aware(datetime(2018, 6, 5)),
        end=timezone.make_aware(datetime(2018, 10, 4)),
    )

    with raises(exceptions.ValidationError) as e:
        deadline2.clean()

    assert "You can only have one deadline of type refund" in str(e.value) 
Example 14
Project: opencraft   Author: open-craft   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_get_billing_period_partial_month_server(self):
        """
        This method will test billing dates for given months when servers
        were only created in the middle of the month.
        """

        # This will test appservers that were started during the month
        # but kept running after the month is over.
        invoice_month = self._generate_invoice_date(2017, 9)
        self.appserver.created = invoice_month + timedelta(days=10)
        first_billing_day, last_billing_day = get_billing_period(self.appserver, invoice_month)

        self.assertEqual(first_billing_day.date(), timezone.make_aware(datetime(2017, 9, 11)).date())
        self.assertEqual(last_billing_day.date(), timezone.make_aware(datetime(2017, 9, 30)).date())

        # This will test appservers that were started during the month
        # and terminated during the month.
        invoice_month = self._generate_invoice_date(2017, 9)
        self.appserver.created = invoice_month + timedelta(days=10)
        self.appserver.terminated = invoice_month + timedelta(days=20)
        first_billing_day, last_billing_day = get_billing_period(self.appserver, invoice_month)

        self.assertEqual(first_billing_day.date(), timezone.make_aware(datetime(2017, 9, 11)).date())
        self.assertEqual(last_billing_day.date(), timezone.make_aware(datetime(2017, 9, 21)).date()) 
Example 15
Project: opencraft   Author: open-craft   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def _generate_invoice_date(year=datetime.now().year, month=1, this_month=False):
        """
        Generates a date for the given year and month which starts with
        the day 1.

        :param year: The year of the invoice.
        :param month: The month of the invoice.
        :param this_month: If provided will create an invoice date for the
                           current month of the year.
        :return: A timezone-aware datetime object.
        """
        if this_month:
            now = timezone.now()
            date = datetime(now.year, now.month, 1)
        else:
            date = datetime(year, month, 1)

        return timezone.make_aware(date) 
Example 16
Project: opencraft   Author: open-craft   File: views.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def report(request, organization, year, month):
    """
    Report view
    """
    try:
        invoice_start_date = timezone.make_aware(datetime(int(year), int(month), 1))
    except ValueError:
        return HttpResponseBadRequest(
            content='<h1>Bad Request</h1>'
                    '<p>Error when processing given date, consider using parameters within range</p>'
        )

    organization = get_object_or_404(Organization, github_handle=organization)
    forks_instances = generate_watched_forks_instances(organization)
    billing_data, total = generate_charges(forks_instances, invoice_start_date)

    return render(request, 'report.html', context={
        'year': year,
        'month': month,
        'month_name': calendar.month_name[int(month)],
        'organization': organization,
        'billing_data': billing_data,
        'total': total,
    }) 
Example 17
Project: django-modelcluster   Author: wagtail   File: models.py    License: 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 18
Project: rssant   Author: anyant   File: validator.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def datetime_validator(compiler, format='%Y-%m-%dT%H:%M:%S.%fZ', output_object=False):
    def validate(value):
        try:
            if not isinstance(value, datetime.datetime):
                value = parse_datetime(value)
                if value is None:
                    raise Invalid('not well formatted datetime')
            if not timezone.is_aware(value):
                value = timezone.make_aware(value, timezone=timezone.utc)
            # https://bugs.python.org/issue13305
            if value.year < 1000:
                raise Invalid('not support datetime before year 1000')
            if value.year > 2999:
                raise Invalid('not support datetime after year 2999')
            if output_object:
                return value
            else:
                return value.strftime(format)
        except Invalid:
            raise
        except Exception as ex:
            raise Invalid('invalid datetime') from ex
    return validate 
Example 19
Project: janeway   Author: BirkbeckCTP   File: shared.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def parse_date(date_string, is_iso):
    """ Parse a date from a string according to timezone-specific settings

    :param date_string: the date string to be parsed
    :param is_iso: whether or not to use ISO-specific formatting settings ("%Y-%m-%dT%H:%M:%S" if True, otherwise
    "%Y-%m-%d"
    :return: a timezone object of the parsed date
    """
    if date_string is not None and date_string != "":
        if is_iso:
            return timezone.make_aware(datetime.strptime(date_string, "%Y-%m-%dT%H:%M:%S"),
                                       timezone.get_current_timezone())
        else:
            return timezone.make_aware(datetime.strptime(date_string, "%Y-%m-%d"), timezone.get_current_timezone())
    else:
        print("Returning current datetime as no valid datetime was given")
        return timezone.now() 
Example 20
Project: graphene-django-extras   Author: eamigo86   File: date.py    License: 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 21
Project: openduty   Author: ustream   File: escalation_helper.py    License: MIT License 6 votes vote down vote up
def get_events_users_inbetween(calendar, since, until):
    delta = until - since
    result = {}
    for i in range(delta.days + 1):
        that_day = since + timedelta(days=i)
        that_day = timezone.make_aware(that_day, timezone.get_current_timezone())
        day = Day(calendar.events.all(), that_day)
        for o in day.get_occurrences():
            if o.start <= that_day <= o.end:
                usernames = o.event.title.split(',')
                for username in usernames:
                    if username not in result.keys():
                        user_instance = User.objects.get(username=username.strip())
                        result[username] = {"start": o.start, "person": username.strip(), "end": o.end,
                                            "email": user_instance.email}
                    else:
                        result[username]["end"] = o.end
    return result.values() 
Example 22
Project: zing   Author: evernote   File: invoice.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_invoice_get_rates_inconsistent_hourly_paidtask_rates(member):
    PAID_TASK_RATE_ONE = 0.5
    PAID_TASK_RATE_TWO = 0.2

    month = timezone.make_aware(timezone.datetime(2014, 4, 1))

    paid_task_kwargs = {
        "rate": PAID_TASK_RATE_ONE,  # Note how this doesn't match user's rate
        "datetime": month,
        "user": member,
        "task_type": PaidTaskTypes.HOURLY_WORK,
    }

    PaidTaskFactory(**paid_task_kwargs)
    PaidTaskFactory(**dict(paid_task_kwargs, rate=PAID_TASK_RATE_TWO))
    invoice = Invoice(member, FAKE_CONFIG, month=month)

    with pytest.raises(ValueError) as e:
        invoice.get_rates()

    assert "Multiple HOURLY_WORK rate values for user %s" % (member.username) in str(
        e.value
    ) 
Example 23
Project: zing   Author: evernote   File: invoice.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_invoice_get_rates_user(member):
    """Tests that `Invoice.get_rates()` returns the rates set for users in their
    user model.
    """
    USER_RATE = 0.5

    # Set some user rate
    member.rate = USER_RATE
    member.review_rate = USER_RATE
    member.hourly_rate = USER_RATE
    member.save()

    month = timezone.make_aware(timezone.datetime(2014, 4, 1))
    invoice = Invoice(member, FAKE_CONFIG, month=month)

    rate, review_rate, hourly_rate = invoice.get_rates()
    assert rate == USER_RATE
    assert review_rate == USER_RATE
    assert hourly_rate == USER_RATE 
Example 24
Project: Servo   Author: fpsw   File: checkescalations.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def handle(self, *args, **options):
        # get local user to create notes as
        uid = Configuration.conf('imap_act')
        
        if empty(uid):
            raise ConfigurationError('Incoming message user not defined')

        user = User.objects.get(pk=uid)
        tz = timezone.get_current_timezone()
        
        for i in Escalation.objects.exclude(Q(escalation_id='') | Q(status='C')):
            # connect per-user since the escalations can be under different ship-tos
            try:
                i.gsx_account.connect(i.created_by)
            except Exception:
                continue # skip auth errors so we don't get stuck

            r = i.get_escalation().lookup()
            aware = timezone.make_aware(r.lastModifiedTimestamp, tz)

            if aware < i.updated_at: # hasn't been updated
                continue

            try:
                parent = i.note_set.latest()
            except Note.DoesNotExist:
                continue

            bodies = [n.body for n in i.note_set.all()]

            for x in r.escalationNotes.iterchildren():
                if x.text in bodies: # skip notes we already have
                    continue

                note = Note(created_by=user, escalation=i, body=x.text)
                parent.add_reply(note)
                note.save()

            i.updated_at = timezone.now()
            i.status = r.escalationStatus
            i.save() 
Example 25
Project: normandy   Author: mozilla   File: utils.py    License: Mozilla Public License 2.0 5 votes vote down vote up
def aware_datetime(*args, **kwargs):
    """Return an aware datetime using Django's configured timezone."""
    return timezone.make_aware(datetime(*args, **kwargs)) 
Example 26
Project: jbox   Author: jpush   File: fields.py    License: 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 27
Project: GTDWeb   Author: lanbing510   File: dates.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _make_date_lookup_arg(self, value):
        """
        Convert a date into a datetime when the date field is a DateTimeField.

        When time zone support is enabled, `date` is assumed to be in the
        current time zone, so that displayed items are consistent with the URL.
        """
        if self.uses_datetime_field:
            value = datetime.datetime.combine(value, datetime.time.min)
            if settings.USE_TZ:
                value = timezone.make_aware(value, timezone.get_current_timezone())
        return value 
Example 28
Project: GTDWeb   Author: lanbing510   File: operations.py    License: GNU General Public License v2.0 5 votes vote down vote up
def year_lookup_bounds_for_datetime_field(self, value):
        """
        Returns a two-elements list with the lower and upper bound to be used
        with a BETWEEN operator to query a DateTimeField value using a year
        lookup.

        `value` is an int, containing the looked-up year.
        """
        first = datetime.datetime(value, 1, 1)
        second = datetime.datetime(value, 12, 31, 23, 59, 59, 999999)
        if settings.USE_TZ:
            tz = timezone.get_current_timezone()
            first = timezone.make_aware(first, tz)
            second = timezone.make_aware(second, tz)
        return [first, second] 
Example 29
Project: GTDWeb   Author: lanbing510   File: base.py    License: GNU General Public License v2.0 5 votes vote down vote up
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(" ")) 
Example 30
Project: GTDWeb   Author: lanbing510   File: expressions.py    License: GNU General Public License v2.0 5 votes vote down vote up
def convert_value(self, value, expression, connection, context):
        if settings.USE_TZ:
            if value is None:
                raise ValueError(
                    "Database returned an invalid value in QuerySet.datetimes(). "
                    "Are time zone definitions for your database and pytz installed?"
                )
            value = value.replace(tzinfo=None)
            value = timezone.make_aware(value, self.tzinfo)
        return value