當前位置: 首頁>>代碼示例>>Python>>正文


Python timezone.make_aware方法代碼示例

本文整理匯總了Python中django.utils.timezone.make_aware方法的典型用法代碼示例。如果您正苦於以下問題:Python timezone.make_aware方法的具體用法?Python timezone.make_aware怎麽用?Python timezone.make_aware使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在django.utils.timezone的用法示例。


在下文中一共展示了timezone.make_aware方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: from_current_timezone

# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import make_aware [as 別名]
def from_current_timezone(value):
    """
    When time zone support is enabled, convert naive datetimes
    entered in the current time zone to aware datetimes.
    """
    if settings.USE_TZ and value is not None and timezone.is_naive(value):
        current_timezone = timezone.get_current_timezone()
        try:
            return timezone.make_aware(value, current_timezone)
        except Exception:
            message = _(
                '%(datetime)s couldn\'t be interpreted '
                'in time zone %(current_timezone)s; it '
                'may be ambiguous or it may not exist.'
            )
            params = {'datetime': value, 'current_timezone': current_timezone}
            six.reraise(ValidationError, ValidationError(
                message,
                code='ambiguous_timezone',
                params=params,
            ), sys.exc_info()[2])
    return value 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:24,代碼來源:utils.py

示例2: adapt_datetime_with_timezone_support

# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import make_aware [as 別名]
def adapt_datetime_with_timezone_support(value, conv):
    # Equivalent to DateTimeField.get_db_prep_value. Used only by raw SQL.
    if settings.USE_TZ:
        if timezone.is_naive(value):
            warnings.warn("MySQL received a naive datetime (%s)"
                          " while time zone support is active." % value,
                          RuntimeWarning)
            default_timezone = timezone.get_default_timezone()
            value = timezone.make_aware(value, default_timezone)
        value = value.astimezone(timezone.utc).replace(tzinfo=None)
    return Thing2Literal(value.strftime("%Y-%m-%d %H:%M:%S.%f"), conv)

# MySQLdb-1.2.1 returns TIME columns as timedelta -- they are more like
# timedelta in terms of actual behavior as they are signed and include days --
# and Django expects time, so we still need to override that. We also need to
# add special handling for SafeText and SafeBytes as MySQLdb's type
# checking is too tight to catch those (see Django ticket #6052).
# Finally, MySQLdb always returns naive datetime objects. However, when
# timezone support is active, Django expects timezone-aware datetime objects. 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:21,代碼來源:base.py

示例3: get_prep_value

# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import make_aware [as 別名]
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 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:20,代碼來源:__init__.py

示例4: parse_date_input

# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import make_aware [as 別名]
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 
開發者ID:adamalton,項目名稱:django-csp-reports,代碼行數:20,代碼來源:utils.py

示例5: handle

# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import make_aware [as 別名]
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) 
開發者ID:awemulya,項目名稱:kobo-predict,代碼行數:26,代碼來源:sync_deleted_instances_fix.py

示例6: from_current_timezone

# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import make_aware [as 別名]
def from_current_timezone(value):
    """
    When time zone support is enabled, convert naive datetimes
    entered in the current time zone to aware datetimes.
    """
    if settings.USE_TZ and value is not None and timezone.is_naive(value):
        current_timezone = timezone.get_current_timezone()
        try:
            return timezone.make_aware(value, current_timezone)
        except Exception as exc:
            raise ValidationError(
                _('%(datetime)s couldn\'t be interpreted '
                  'in time zone %(current_timezone)s; it '
                  'may be ambiguous or it may not exist.'),
                code='ambiguous_timezone',
                params={'datetime': value, 'current_timezone': current_timezone}
            ) from exc
    return value 
開發者ID:reBiocoder,項目名稱:bioforum,代碼行數:20,代碼來源:utils.py

示例7: year_lookup_bounds_for_datetime_field

# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import make_aware [as 別名]
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] 
開發者ID:reBiocoder,項目名稱:bioforum,代碼行數:19,代碼來源:operations.py

示例8: convert_value

# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import make_aware [as 別名]
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 
開發者ID:reBiocoder,項目名稱:bioforum,代碼行數:18,代碼來源:datetime.py

示例9: get_prep_value

# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import make_aware [as 別名]
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 
開發者ID:reBiocoder,項目名稱:bioforum,代碼行數:20,代碼來源:__init__.py

示例10: test_conference_cannot_have_two_deadlines_of_type_event

# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import make_aware [as 別名]
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) 
開發者ID:pythonitalia,項目名稱:pycon,代碼行數:22,代碼來源:test_models.py

示例11: test_conference_cannot_have_two_deadlines_of_type_cfp

# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import make_aware [as 別名]
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) 
開發者ID:pythonitalia,項目名稱:pycon,代碼行數:22,代碼來源:test_models.py

示例12: test_conference_cannot_have_two_deadlines_of_type_voting

# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import make_aware [as 別名]
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) 
開發者ID:pythonitalia,項目名稱:pycon,代碼行數:22,代碼來源:test_models.py

示例13: test_conference_cannot_have_two_deadlines_of_type_refund

# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import make_aware [as 別名]
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) 
開發者ID:pythonitalia,項目名稱:pycon,代碼行數:22,代碼來源:test_models.py

示例14: test_get_billing_period_partial_month_server

# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import make_aware [as 別名]
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()) 
開發者ID:open-craft,項目名稱:opencraft,代碼行數:26,代碼來源:tests.py

示例15: _generate_invoice_date

# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import make_aware [as 別名]
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) 
開發者ID:open-craft,項目名稱:opencraft,代碼行數:20,代碼來源:tests.py


注:本文中的django.utils.timezone.make_aware方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。