def correct_awareness(value):
"""Fix the given datetime timezone awareness."""
if isinstance(value, datetime):
if settings.USE_TZ:
return make_aware(value)
elif timezone.is_aware(value):
default_tz = timezone.get_default_timezone()
return timezone.make_naive(value, default_tz)
return value
python类get_default_timezone()的实例源码
def to_localtime(time):
'''
A function to convert naive datetime to
localtime base on settings
'''
utc_time = time.replace(tzinfo=timezone.utc)
to_zone = timezone.get_default_timezone()
return utc_time.astimezone(to_zone)
def _possibly_make_aware(dt):
"""
Convert a datetime object in the local timezone to aware
in UTC, if USE_TZ is True.
"""
# This function is only needed to help with the deprecations above and can
# be removed in Django 2.0, RemovedInDjango20Warning.
if settings.USE_TZ:
tz = timezone.get_default_timezone()
return timezone.make_aware(dt, tz).astimezone(timezone.utc)
else:
return dt
def default_timezone(self):
return timezone.get_default_timezone() if settings.USE_TZ else None
def get_context_data(self, request, **kwargs):
context = super(CalendarByPeriodsView, self).get_context_data(**kwargs)
calendar = self.object
periods = kwargs.get('periods', None)
try:
date = coerce_date_dict(request.GET)
except ValueError:
raise Http404
if date:
try:
date = datetime.datetime(**date)
except ValueError:
raise Http404
else:
date = timezone.now()
event_list = GET_EVENTS_FUNC(request, calendar)
if 'django_timezone' in self.request.session:
local_timezone = pytz.timezone(request.session['django_timezone'])
else:
local_timezone = timezone.get_default_timezone()
period_objects = {}
for period in periods:
if period.__name__.lower() == 'year':
period_objects[period.__name__.lower()] = period(event_list, date, None, local_timezone)
else:
period_objects[period.__name__.lower()] = period(event_list, date, None, None, local_timezone)
context.update({
'date': date,
'periods': period_objects,
'calendar': calendar,
'weekday_names': weekday_names,
'here': quote(request.get_full_path()),
})
return context
def dateStringsToQ(self, field_name, date_from_str, date_to_str):
"""
Convert the date strings from_date_str and to_date_str into a
set of args in the form
{'<field_name>__gte': <date from>, '<field_name>__lte': <date to>}
where date_from and date_to are Django-timezone-aware dates; then
convert that into a Django Q object
Returns the Q object based on those criteria
"""
# one of the values required for the filter is missing, so set
# it to the one which was supplied
if date_from_str == '':
date_from_str = date_to_str
elif date_to_str == '':
date_to_str = date_from_str
date_from_naive = dateparse.parse_datetime(date_from_str + ' 00:00:00')
date_to_naive = dateparse.parse_datetime(date_to_str + ' 23:59:59')
tz = timezone.get_default_timezone()
date_from = timezone.make_aware(date_from_naive, tz)
date_to = timezone.make_aware(date_to_naive, tz)
args = {}
args[field_name + '__gte'] = date_from
args[field_name + '__lte'] = date_to
return Q(**args)
def _possibly_make_aware(dt):
"""
Convert a datetime object in the local timezone to aware
in UTC, if USE_TZ is True.
"""
# This function is only needed to help with the deprecations above and can
# be removed in Django 2.0, RemovedInDjango20Warning.
if settings.USE_TZ:
tz = timezone.get_default_timezone()
return timezone.make_aware(dt, tz).astimezone(timezone.utc)
else:
return dt
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(" "))
def default_timezone(self):
return timezone.get_default_timezone() if settings.USE_TZ else None
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(" "))
def from_native(self, value):
if value in validators.EMPTY_VALUES:
return None
if isinstance(value, datetime.datetime):
if timezone and 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
for fmt in self.input_formats:
if fmt.lower() == ISO_8601:
try:
parsed = parse_date(value)
except (ValueError, TypeError):
pass
else:
if parsed is not None:
return parsed
else:
try:
parsed = datetime.datetime.strptime(value, fmt)
except (ValueError, TypeError):
pass
else:
return parsed.date()
msg = self.error_messages['invalid'] % readable_date_formats(self.input_formats)
raise ValidationError(msg)
def from_native(self, value):
if value in validators.EMPTY_VALUES:
return None
if isinstance(value, datetime.datetime):
return value
if isinstance(value, datetime.date):
value = datetime.datetime(value.year, value.month, value.day)
if settings.USE_TZ:
# 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.
warnings.warn("DateTimeField 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)
return value
for fmt in self.input_formats:
if fmt.lower() == ISO_8601:
try:
parsed = parse_datetime(value)
except (ValueError, TypeError):
pass
else:
if parsed is not None:
return parsed
else:
try:
parsed = datetime.datetime.strptime(value, fmt)
except (ValueError, TypeError):
pass
else:
return parsed
msg = self.error_messages['invalid'] % readable_datetime_formats(self.input_formats)
raise ValidationError(msg)
def _pre_save_callback(self, user, upform, *args, **kwargs):
"""
Stuff that needs to be done pre-saving the user object.
"""
# Just to be sure - for a never logged-in user this should be True:
# user.last_login <= user.date_joined
user.last_login = timezone.datetime(1970, 1, 1, 0, 0, 0, 0, timezone.get_default_timezone())
# Update username to email for common users
user.username = user.email.lower()
# Update user default datacenter
user.default_dc = self.request.dc
return user, upform
# noinspection PyUnusedLocal
def _possibly_make_aware(dt):
"""
Convert a datetime object in the local timezone to aware
in UTC, if USE_TZ is True.
"""
# This function is only needed to help with the deprecations above and can
# be removed in Django 2.0, RemovedInDjango20Warning.
if settings.USE_TZ:
tz = timezone.get_default_timezone()
return timezone.make_aware(dt, tz).astimezone(timezone.utc)
else:
return dt
def _possibly_make_aware(dt):
"""
Convert a datetime object in the local timezone to aware
in UTC, if USE_TZ is True.
"""
# This function is only needed to help with the deprecations above and can
# be removed in Django 2.0, RemovedInDjango20Warning.
if settings.USE_TZ:
tz = timezone.get_default_timezone()
return timezone.make_aware(dt, tz).astimezone(timezone.utc)
else:
return dt
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:
raise exceptions.ValidationError(
self.error_messages['invalid_date'],
code='invalid_date',
params={'value': value},
)
raise exceptions.ValidationError(
self.error_messages['invalid'],
code='invalid',
params={'value': value},
)
def __init__(self, obj):
self.data = obj
self.timezone = None
# We only support timezone when formatting datetime objects,
# not date objects (timezone information not appropriate),
# or time objects (against established django policy).
if isinstance(obj, datetime.datetime):
if is_naive(obj):
self.timezone = get_default_timezone()
else:
self.timezone = obj.tzinfo
def I(self):
"'1' if Daylight Savings Time, '0' otherwise."
try:
if self.timezone and self.timezone.dst(self.data):
return '1'
else:
return '0'
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 ''
def _possibly_make_aware(dt):
"""
Convert a datetime object in the local timezone to aware
in UTC, if USE_TZ is True.
"""
# This function is only needed to help with the deprecations above and can
# be removed in Django 2.0, RemovedInDjango20Warning.
if settings.USE_TZ:
tz = timezone.get_default_timezone()
return timezone.make_aware(dt, tz).astimezone(timezone.utc)
else:
return dt
def history(self, request, pk=None):
instance = self.get_object()
user = request.query_params.get('user', None) # Default to all users
start = request.query_params.get('start', None) # In YYYY-MM-DD format
if start:
start = datetime.datetime.strptime(start, '%Y-%m-%d')
else:
start = datetime.datetime.min
start = timezone.make_aware(start, timezone.get_default_timezone())
end = request.query_params.get('end', None) # In YYYY-MM-DD format
if end:
end = datetime.datetime.strptime(start, '%Y-%m-%d')
else:
end = datetime.datetime.today()
end = timezone.make_aware(end, timezone.get_default_timezone())
history = []
for v, version in enumerate(Version.objects.get_for_object(instance).reverse()):
if (user is not None and version.revision.user.username != user) \
or version.revision.date_created < start \
or version.revision.date_created > end:
continue
history.append({'version': v,
'created': version.revision.date_created.strftime('%Y-%m-%d %H:%M:%S'),
'user': version.revision.user.username,
'data': version.field_dict})
return Response(history, status=200)