本文整理匯總了Python中django.utils.timezone.get_default_timezone方法的典型用法代碼示例。如果您正苦於以下問題:Python timezone.get_default_timezone方法的具體用法?Python timezone.get_default_timezone怎麽用?Python timezone.get_default_timezone使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類django.utils.timezone
的用法示例。
在下文中一共展示了timezone.get_default_timezone方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: datetime
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import get_default_timezone [as 別名]
def datetime(self, field=None, val=None):
"""
Returns a random datetime. If 'val' is passed, a datetime within two
years of that date will be returned.
"""
if val is None:
def source():
tzinfo = get_default_timezone() if settings.USE_TZ else None
return datetime.fromtimestamp(randrange(1, 2100000000),
tzinfo)
else:
def source():
tzinfo = get_default_timezone() if settings.USE_TZ else None
return datetime.fromtimestamp(int(val.strftime("%s")) +
randrange(-365*24*3600*2, 365*24*3600*2),
tzinfo)
return self.get_allowed_value(source, field)
示例2: adapt_datetime_with_timezone_support
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import get_default_timezone [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 get_default_timezone [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: T
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import get_default_timezone [as 別名]
def T(self):
"""
Time zone of this machine; e.g. 'EST' or 'MDT'.
If timezone information is not available, return an empty string.
"""
if not self.timezone:
return ""
name = None
try:
name = self.timezone.tzname(self.data)
except Exception:
# pytz raises AmbiguousTimeError during the autumn DST change.
# This happens mainly when __init__ receives a naive datetime
# and sets self.timezone = get_default_timezone().
pass
if name is None:
name = self.format('O')
return str(name)
示例5: Z
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import get_default_timezone [as 別名]
def Z(self):
"""
Time zone offset in seconds (i.e. '-43200' to '43200'). The offset for
timezones west of UTC is always negative, and for those east of UTC is
always positive.
If timezone information is not available, return an empty string.
"""
if not self.timezone:
return ""
try:
offset = self.timezone.utcoffset(self.data)
except Exception:
# pytz raises AmbiguousTimeError during the autumn DST change.
# This happens mainly when __init__ receives a naive datetime
# and sets self.timezone = get_default_timezone().
return ""
# `offset` is a datetime.timedelta. For negative values (to the west of
# UTC) only days can be negative (days=-1) and seconds are always
# positive. e.g. UTC-1 -> timedelta(days=-1, seconds=82800, microseconds=0)
# Positive offsets have days=0
return offset.days * 86400 + offset.seconds
示例6: get_prep_value
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import get_default_timezone [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
示例7: get_field_value
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import get_default_timezone [as 別名]
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())
示例8: _check_single_paidtask
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import get_default_timezone [as 別名]
def _check_single_paidtask(invoice, amount):
server_tz = timezone.get_default_timezone()
local_now = timezone.localtime(invoice.now, server_tz)
current_month_start = local_now.replace(
day=1, hour=0, minute=0, second=0, microsecond=0
)
PaidTask.objects.get(
task_type=PaidTaskTypes.CORRECTION,
amount=(-1) * amount,
datetime=invoice.month_end,
description="Carryover to the next month",
user=invoice.user,
)
PaidTask.objects.get(
task_type=PaidTaskTypes.CORRECTION,
amount=amount,
datetime=current_month_start,
description="Carryover from the previous month",
user=invoice.user,
)
示例9: get_max_month_datetime
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import get_default_timezone [as 別名]
def get_max_month_datetime(dt):
"""Returns the datetime representing the last second of the month with
respect to the `dt` aware datetime.
"""
days_in_month = calendar.monthrange(dt.year, dt.month)[1]
tz = timezone.get_default_timezone()
new_dt = tz.normalize(dt.replace(day=days_in_month),)
# DST adjustments could have shifted the month or day
if new_dt.month != dt.month:
new_dt = new_dt.replace(month=dt.month)
if new_dt.day != days_in_month:
new_dt = new_dt.replace(day=days_in_month)
return new_dt.replace(hour=23, minute=59, second=59, microsecond=0)
示例10: _format_parameters
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import get_default_timezone [as 別名]
def _format_parameters( self, parameters ):
parameters = list( parameters )
for index in range( len( parameters ) ):
# With raw SQL queries, datetimes can reach this function
# without being converted by DateTimeField.get_db_prep_value.
if settings.USE_TZ and isinstance( parameters[index], datetime.datetime ):
param = parameters[index]
if timezone.is_naive( param ):
warnings.warn(u"Received a naive datetime (%s)"
u" while time zone support is active." % param,
RuntimeWarning)
default_timezone = timezone.get_default_timezone()
param = timezone.make_aware( param, default_timezone )
param = param.astimezone(timezone.utc).replace(tzinfo=None)
parameters[index] = param
return tuple( parameters )
# Over-riding this method to modify SQLs which contains format parameter to qmark.
示例11: T
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import get_default_timezone [as 別名]
def T(self):
"""
Time zone of this machine; e.g. 'EST' or 'MDT'.
If timezone information is not available, this method returns
an empty string.
"""
if not self.timezone:
return ""
name = None
try:
name = self.timezone.tzname(self.data)
except Exception:
# pytz raises AmbiguousTimeError during the autumn DST change.
# This happens mainly when __init__ receives a naive datetime
# and sets self.timezone = get_default_timezone().
pass
if name is None:
name = self.format('O')
return six.text_type(name)
示例12: Z
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import get_default_timezone [as 別名]
def Z(self):
"""
Time zone offset in seconds (i.e. '-43200' to '43200'). The offset for
timezones west of UTC is always negative, and for those east of UTC is
always positive.
If timezone information is not available, this method returns
an empty string.
"""
if not self.timezone:
return ""
try:
offset = self.timezone.utcoffset(self.data)
except Exception:
# pytz raises AmbiguousTimeError during the autumn DST change.
# This happens mainly when __init__ receives a naive datetime
# and sets self.timezone = get_default_timezone().
return ""
# `offset` is a datetime.timedelta. For negative values (to the west of
# UTC) only days can be negative (days=-1) and seconds are always
# positive. e.g. UTC-1 -> timedelta(days=-1, seconds=82800, microseconds=0)
# Positive offsets have days=0
return offset.days * 86400 + offset.seconds
示例13: adapt_datetime_with_timezone_support
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import get_default_timezone [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"), 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.
示例14: to_python
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import get_default_timezone [as 別名]
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)
示例15: test_serialize_datetime
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import get_default_timezone [as 別名]
def test_serialize_datetime(self):
self.assertSerializedEqual(datetime.datetime.utcnow())
self.assertSerializedEqual(datetime.datetime.utcnow)
self.assertSerializedEqual(datetime.datetime.today())
self.assertSerializedEqual(datetime.datetime.today)
self.assertSerializedEqual(datetime.date.today())
self.assertSerializedEqual(datetime.date.today)
self.assertSerializedEqual(datetime.datetime.now().time())
self.assertSerializedEqual(datetime.datetime(2014, 1, 1, 1, 1, tzinfo=get_default_timezone()))
self.assertSerializedEqual(datetime.datetime(2013, 12, 31, 22, 1, tzinfo=FixedOffset(180)))
self.assertSerializedResultEqual(
datetime.datetime(2014, 1, 1, 1, 1),
("datetime.datetime(2014, 1, 1, 1, 1)", {'import datetime'})
)
self.assertSerializedResultEqual(
datetime.datetime(2012, 1, 1, 1, 1, tzinfo=utc),
(
"datetime.datetime(2012, 1, 1, 1, 1, tzinfo=utc)",
{'import datetime', 'from django.utils.timezone import utc'},
)
)