def to_current_timezone(value):
"""
When time zone support is enabled, convert aware datetimes
to naive dateimes in the current time zone for display.
"""
if settings.USE_TZ and value is not None and timezone.is_aware(value):
current_timezone = timezone.get_current_timezone()
return timezone.make_naive(value, current_timezone)
return value
python类make_naive()的实例源码
def ensure_timezone(dateTime,timeZone=None):
'''
Since this project is designed to be used in both time-zone aware
and naive environments, this utility just returns a datetime as either
aware or naive depending on whether time zone support is enabled.
'''
if is_aware(dateTime) and not getattr(settings,'USE_TZ',False):
return make_naive(dateTime,timezone=timeZone)
if is_naive(dateTime) and getattr(settings,'USE_TZ',False):
return make_aware(dateTime,timezone=timeZone)
# If neither condition is met, then we can return what was passed
return dateTime
def ensure_localtime(dateTime):
if not getattr(settings,'USE_TZ',False):
return make_naive(dateTime) if is_aware(dateTime) else dateTime
else:
return localtime(make_aware(dateTime) if is_naive(dateTime) else dateTime)
def enforce_timezone(self, value):
"""
When `self.default_timezone` is `None`, always return naive datetimes.
When `self.default_timezone` is not `None`, always return aware datetimes.
"""
field_timezone = getattr(self, 'timezone', self.default_timezone())
if (field_timezone is not None) and not timezone.is_aware(value):
return timezone.make_aware(value, field_timezone)
elif (field_timezone is None) and timezone.is_aware(value):
return timezone.make_naive(value, timezone.UTC())
return value
def to_current_timezone(value):
"""
When time zone support is enabled, convert aware datetimes
to naive datetimes in the current time zone for display.
"""
if settings.USE_TZ and value is not None and timezone.is_aware(value):
current_timezone = timezone.get_current_timezone()
return timezone.make_naive(value, current_timezone)
return value
def to_current_timezone(value):
"""
When time zone support is enabled, convert aware datetimes
to naive datetimes in the current time zone for display.
"""
if settings.USE_TZ and value is not None and timezone.is_aware(value):
current_timezone = timezone.get_current_timezone()
return timezone.make_naive(value, current_timezone)
return value
def to_current_timezone(value):
"""
When time zone support is enabled, convert aware datetimes
to naive dateimes in the current time zone for display.
"""
if settings.USE_TZ and value is not None and timezone.is_aware(value):
current_timezone = timezone.get_current_timezone()
return timezone.make_naive(value, current_timezone)
return value
def to_current_timezone(value):
"""
When time zone support is enabled, convert aware datetimes
to naive dateimes in the current time zone for display.
"""
if settings.USE_TZ and value is not None and timezone.is_aware(value):
current_timezone = timezone.get_current_timezone()
return timezone.make_naive(value, current_timezone)
return value
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 to_current_timezone(value):
"""
When time zone support is enabled, convert aware datetimes
to naive datetimes in the current time zone for display.
"""
if settings.USE_TZ and value is not None and timezone.is_aware(value):
current_timezone = timezone.get_current_timezone()
return timezone.make_naive(value, current_timezone)
return value
def to_current_timezone(value):
"""
When time zone support is enabled, convert aware datetimes
to naive datetimes in the current time zone for display.
"""
if settings.USE_TZ and value is not None and timezone.is_aware(value):
current_timezone = timezone.get_current_timezone()
return timezone.make_naive(value, current_timezone)
return value
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 to_current_timezone(value):
"""
When time zone support is enabled, convert aware datetimes
to naive datetimes in the current time zone for display.
"""
if settings.USE_TZ and value is not None and timezone.is_aware(value):
current_timezone = timezone.get_current_timezone()
return timezone.make_naive(value, current_timezone)
return value
def to_current_timezone(value):
"""
When time zone support is enabled, convert aware datetimes
to naive datetimes in the current time zone for display.
"""
if settings.USE_TZ and value is not None and timezone.is_aware(value):
current_timezone = timezone.get_current_timezone()
return timezone.make_naive(value, current_timezone)
return value
def get_or_create_session_id(self, user_id):
session_mapping = get_object_or_None(SessionLookup, user_id=user_id)
# if its missing create a new one.
if session_mapping is None:
session_mapping = SessionLookup.objects.create(
user_id=user_id,
session_id=generate_session_id()
)
else:
session = ussd_session(session_mapping.session_id)
# get last time session was updated
if session.get(ussd_airflow_variables.last_update):
last_updated = utilities.string_to_datetime(
session[ussd_airflow_variables.last_update])
else:
last_updated = timezone.make_naive(session_mapping.updated_at)
# check inactivity or if session has been closed
inactivity_duration = (datetime.now() - last_updated).total_seconds()
if inactivity_duration > self.expiry or \
session.get(ussd_airflow_variables.expiry):
# update session_mapping with the new session_id
session_mapping.session_id = generate_session_id()
session_mapping.save()
return session_mapping.session_id
def test_csv_okay(self):
"""
Export tags as CSV.
"""
_sign_in(self.admin)
url = reverse(
'export:tags', kwargs={"project_id": self.project.pk})
resp = self.client.post(url)
self.assertEqual(200, resp.status_code)
tags = list(read_csv_to_dict(resp.content, encoding='utf-16'))
self.assertEqual(2, len(tags))
tag1 = next(t for t in tags if long(t['id']) == self.tag1.pk)
self.assertEqual(self.tag1.name, tag1['name'])
self.assertEqual(str(self.tag1.description or ''), tag1['description'])
self.assertEqual(str(self.tag1.image_url or ''), tag1['image_url'])
self.assertEqual(
timezone.make_naive(
self.tag1.created, timezone.utc
).strftime("%Y-%m-%d %H:%M:%S+00:00"),
datetime.datetime.strptime(tag1['created'], '%Y-%m-%d %H:%M:%S.%f+00:00').strftime("%Y-%m-%d %H:%M:%S+00:00"))
self.assertEqual(
timezone.make_naive(
self.tag1.modified, timezone.utc
).strftime("%Y-%m-%d %H:%M:%S+00:00"),
datetime.datetime.strptime(tag1['modified'], '%Y-%m-%d %H:%M:%S.%f+00:00').strftime("%Y-%m-%d %H:%M:%S+00:00"))
self.assertEqual('2', tag1['instance_count'])
self.assertEqual('', tag1['parent_id'])
def from_instance(cls, project):
"""
Factory method for creating a project document from
a Project model instance.
"""
doc = cls(doc_id=str(project.pk))
copy_attrs = ['name', 'description']
for attr in copy_attrs:
setattr(doc, attr, getattr(project, attr, None))
doc.id = unicode(project.pk)
# make datetimes timezone naive as appengine doesnt support
# indexing aware datetime objects which is annoying
doc.created = timezone.make_naive(project.created, timezone.utc)
doc.modified = timezone.make_naive(project.modified, timezone.utc)
# manually add data that we cant directly copy from the instance
if project.owner:
doc.owner_id = unicode(project.owner.id)
doc.owner_name = '%s %s' % (
project.owner.first_name, project.owner.last_name)
# add assigned users
doc.assigned_users = ' '.join(
str(user_id) for user_id in project.projectusers.filter(
is_pending=False, is_assigned=True).values_list(
'user_id', flat=True)).strip()
# build ngrams
doc.n_grams = cls.make_ngrams(project.name)
# return completed doc.
return doc
def to_tuple(self):
return self.pk, int(make_naive(self.datetime).timestamp())
def cache_key(self):
return self.build_cache_key(self.pk, int(make_naive(self.datetime).timestamp()))
def last_update_cache_key(self):
last_update = self.created if self.last_update_id is None else self.last_update.datetime
return int_to_base36(self.last_update_id or 0)+'_'+int_to_base36(int(make_naive(last_update).timestamp()))