Python django.utils.timezone.make_aware() Examples

The following are 30 code examples of django.utils.timezone.make_aware(). 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: validator.py    From rssant with BSD 3-Clause "New" or "Revised" License 7 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 #2
Source File: views.py    From opencraft with 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 #3
Source File: sync_deleted_instances_fix.py    From kobo-predict with 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 #4
Source File: tests.py    From opencraft with 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 #5
Source File: tests.py    From opencraft with 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 #6
Source File: datetime.py    From bioforum with 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 #7
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 #8
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 #9
Source File: __init__.py    From bioforum with 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
Source File: utils.py    From django-csp-reports with 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 #11
Source File: invoice.py    From zing with 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 #12
Source File: test_models.py    From pycon with 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 #13
Source File: test_models.py    From pycon with 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 #14
Source File: __init__.py    From GTDWeb with 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 #15
Source File: test_models.py    From pycon with 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 #16
Source File: shared.py    From janeway with 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 #17
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 #18
Source File: test_models.py    From pycon with 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 #19
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 #20
Source File: invoice.py    From zing with 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 #21
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 #22
Source File: escalation_helper.py    From openduty with 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 #23
Source File: operations.py    From bioforum with 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 #24
Source File: test_utils.py    From django-subscriptions with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_as_date_aware(self):
        dt = datetime(2019, 6, 13, 23, 30)
        dt = timezone.make_aware(dt, timezone=timezone.utc)
        # localise will push from 23:30 -> 9:30 the next day
        self.assertEqual(as_date(dt), datetime(2019, 6, 14).date()) 
Example #25
Source File: raw_parser.py    From rssant with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _normalize_date(self, value) -> datetime.datetime:
        if not value:
            return None
        try:
            if isinstance(value, list) and len(value) == 9:
                value = tuple(value)
            if isinstance(value, tuple):
                try:
                    timestamp = time.mktime(value)
                except OverflowError:
                    return None
                value = datetime.datetime.fromtimestamp(timestamp, tz=UTC)
            elif not isinstance(value, datetime.datetime):
                value = parse_datetime(value)
                if value is None:
                    return None
        except Exception as ex:
            LOG.warning('normalize date failed, value=%r: %s', value, ex)
            return None
        if not timezone.is_aware(value):
            value = timezone.make_aware(value, timezone=UTC)
        # https://bugs.python.org/issue13305
        if value.year < 1000:
            return None
        if value.year > 2999:
            return None
        return value 
Example #26
Source File: tests.py    From opencraft with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_get_billing_period_terminated_server(self):
        """
        Tests the calculated billing dates (start, and end) for a given
        terminated appserver before the month of the invoice month.
        """
        invoice_month = self._generate_invoice_date(this_month=True)

        # The app server was created in the past and terminated before the billing start date
        created = invoice_month - timedelta(weeks=10)
        terminated = invoice_month - timedelta(weeks=7)

        self.appserver.created = created
        self.appserver.terminated = terminated
        first_billing_day, last_billing_day = get_billing_period(self.appserver, invoice_month)

        self.assertIsNone(first_billing_day)
        self.assertIsNone(last_billing_day)

        # An invoice from the past
        invoice_month = timezone.make_aware(datetime(2016, 10, 3))
        # The app server was created in the past and terminated before the billing start date
        created = invoice_month - timedelta(weeks=10)
        terminated = invoice_month - timedelta(weeks=7)

        self.appserver.created = created
        self.appserver.terminated = terminated
        first_billing_day, last_billing_day = get_billing_period(self.appserver, invoice_month)

        self.assertIsNone(first_billing_day)
        self.assertIsNone(last_billing_day) 
Example #27
Source File: export.py    From zulip with Apache License 2.0 5 votes vote down vote up
def floatify_datetime_fields(data: TableData, table: TableName) -> None:
    for item in data[table]:
        for field in DATE_FIELDS[table]:
            orig_dt = item[field]
            if orig_dt is None:
                continue
            if timezone_is_naive(orig_dt):
                logging.warning("Naive datetime:", item)
                dt = timezone_make_aware(orig_dt)
            else:
                dt = orig_dt
            utc_naive  = dt.replace(tzinfo=None) - dt.utcoffset()
            item[field] = (utc_naive - datetime.datetime(1970, 1, 1)).total_seconds() 
Example #28
Source File: test_models.py    From pycon with MIT License 5 votes vote down vote up
def test_deadline_start_cannot_be_after_end(deadline_factory):
    deadline = deadline_factory(
        start=timezone.make_aware(datetime(2018, 5, 5)),
        end=timezone.make_aware(datetime(2018, 4, 4)),
    )

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

    assert "Start date cannot be after end" in str(e.value) 
Example #29
Source File: TimeUtils.py    From civet with Apache License 2.0 5 votes vote down vote up
def get_local_timestamp():
    return math.floor((timezone.localtime(
        timezone.now()) - timezone.make_aware(datetime.datetime.fromtimestamp(0))).total_seconds()) 
Example #30
Source File: models.py    From civet with Apache License 2.0 5 votes vote down vote up
def unseen_seconds(self):
        return (timezone.make_aware(datetime.utcnow()) - self.last_seen).total_seconds()