本文整理汇总了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
示例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.
示例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
示例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
示例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)
示例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
示例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]
示例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
示例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
示例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)
示例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)
示例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)
示例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)
示例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())
示例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)