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
python类make_aware()的实例源码
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
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
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.
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
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.
def test_fill_with_duplicate_status(self):
sample_user=twitter.User(
id=718443,
name='Bob Loblaw',
screen_name='bobby',
location='Vancouver, Canada',
verified=True
)
sample_status=twitter.Status(
created_at=datetime.strftime(timezone.make_aware(datetime.now()), '%a %b %d %H:%M:%S +0000 %Y'),
id=1234567,
text='Hello world, again!',
user=sample_user,
retweet_count=1,
favorite_count=5,
)
movie = Movie.objects.get(imdbID="123456")
duplicate_tweet = Tweet().fillWithStatusObject(sample_status, movie)
self.assertEqual(duplicate_tweet.text, 'Hello world')
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
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
def convert_value(self, value, expression, connection, context):
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 and pytz 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
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
def store_event(request, project):
try:
auth_header = validate_auth_header(request, project)
except InvalidAuth as ia:
return JsonResponse({'error': str(ia)}, status=401)
body = request.body
if request.META.get('HTTP_CONTENT_ENCODING') == 'deflate':
body = zlib.decompress(body)
elif auth_header.get('sentry_version') == '5': # Support older versions of Raven
body = zlib.decompress(base64.b64decode(body)).decode('utf8')
body = json.loads(force_text(body))
timestamp = make_aware(datetime.fromtimestamp(float(auth_header['sentry_timestamp'])), timezone=UTC)
with transaction.atomic():
event = Event.objects.create_from_raven(project_id=project, body=body, timestamp=timestamp)
try:
event_received.send(sender=event)
except: # pragma: no cover
logger.warning('event_received signal handling failed', exc_info=True)
if settings.DEBUG:
raise
return JsonResponse({'id': event.id}, status=201)
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
def test_presets(self):
self.assertIs(EquipmentReservation.objects.filter(id=self._joeReservation.id).exists(),
True)
res1 = EquipmentReservation.objects.get(id=self._joeReservation.id)
self.assertEqual(res1.start, timezone.make_aware(datetime.datetime(2050, 3, 11)))
self.assertEqual(res1.end, timezone.make_aware(datetime.datetime(2050, 3, 13)))
self.assertEqual(res1.reserved_for, "An experiment I'm doing")
self.assertEqual(res1.reserved_by, self._joeBloggs)
self.assertEqual(res1.equipment_reserved, self._equipmentSequencer)
self.assertEqual(res1.is_confirmed, False)
self.assertEqual(res1.checked_in, False)
res1 = EquipmentReservation.objects.get(id=self._janeReservation.id)
self.assertEqual(res1.start, timezone.make_aware(datetime.datetime(2050, 3, 14)))
self.assertEqual(res1.end, timezone.make_aware(datetime.datetime(2050, 3, 16)))
self.assertEqual(res1.reserved_for, "Very important sequencing stuff")
self.assertEqual(res1.reserved_by, self._janeDoe)
self.assertEqual(res1.equipment_reserved, self._equipmentSequencer)
self.assertEqual(res1.is_confirmed, False)
self.assertEqual(res1.checked_in, False)
def test_staff_create_autoconfirm(self):
self._asStaff()
new_res = {"start": timezone.make_aware(datetime.datetime(2050, 6, 14)),
"end": timezone.make_aware(datetime.datetime(2050, 6, 16)),
"reserved_for": "Something or other I might want to do",
"reserved_by": self._staffUser.username,
"equipment_reserved": self._equipmentSequencer.name,
"is_confirmed": False,
"checked_in": False}
response = self._client.post("/equipmentreservation/", new_res, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertIs(EquipmentReservation.objects.filter(
reserved_for="Something or other I might want to do").exists(), True)
res1 = EquipmentReservation.objects.get(
reserved_for="Something or other I might want to do")
self.assertEqual(res1.is_confirmed, True)
self.assertEqual(res1.confirmed_by, self._staffUser)
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
def get_modified_time(storage, name):
"""
Get modified time from storage, ensuring the result is a timezone-aware
datetime.
"""
try:
modified_time = storage.modified_time(name)
except OSError:
return 0
except NotImplementedError:
return None
if modified_time and timezone.is_naive(modified_time):
if getattr(settings, 'USE_TZ', False):
default_timezone = timezone.get_default_timezone()
return timezone.make_aware(modified_time, default_timezone)
return modified_time
def save(self, *args, **kwargs):
if self.date_taken is None:
try:
exif_date = self.exif.get('DateTimeOriginal', None)
if exif_date is not None:
d, t = exif_date.split(" ")
year, month, day = d.split(':')
hour, minute, second = t.split(':')
if getattr(settings, "USE_TZ", False):
tz = get_current_timezone()
self.date_taken = make_aware(datetime(
int(year), int(month), int(day),
int(hour), int(minute), int(second)), tz)
else:
self.date_taken = datetime(
int(year), int(month), int(day),
int(hour), int(minute), int(second))
except Exception:
pass
if self.date_taken is None:
self.date_taken = now()
super(Image, self).save(*args, **kwargs)
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
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