def timezone(self):
"""
Time zone for datetimes stored as naive values in the database.
Returns a tzinfo object or None.
This is only needed when time zone support is enabled and the database
doesn't support time zones. (When the database supports time zones,
the adapter handles aware datetimes so Django doesn't need to.)
"""
if not settings.USE_TZ:
return None
elif self.features.supports_timezones:
return None
elif self.settings_dict['TIME_ZONE'] is None:
return timezone.utc
else:
# Only this branch requires pytz.
return pytz.timezone(self.settings_dict['TIME_ZONE'])
python类TIME_ZONE的实例源码
def pootle_context(request):
"""Exposes settings to templates."""
# FIXME: maybe we should expose relevant settings only?
return {
'settings': {
'POOTLE_TITLE': settings.POOTLE_TITLE,
'POOTLE_INSTANCE_ID': settings.POOTLE_INSTANCE_ID,
'POOTLE_CONTACT_ENABLED': (settings.POOTLE_CONTACT_ENABLED and
settings.POOTLE_CONTACT_EMAIL),
'POOTLE_SIGNUP_ENABLED': settings.POOTLE_SIGNUP_ENABLED,
'POOTLE_CACHE_TIMEOUT': settings.POOTLE_CACHE_TIMEOUT,
'TZ': settings.TIME_ZONE,
'TZ_OFFSET': TZ_OFFSET,
'DEBUG': settings.DEBUG,
},
'custom': settings.POOTLE_CUSTOM_TEMPLATE_CONTEXT,
'ALL_LANGUAGES': Language.live.cached_dict(translation.get_language(),
request.user.is_superuser),
'ALL_PROJECTS': Project.objects.cached_dict(request.user),
'SOCIAL_AUTH_PROVIDERS': _get_social_auth_providers(request),
'display_agreement': _agreement_context(request),
}
def _select_locale(self, request):
supported = request.event.locales if (hasattr(request, 'event') and request.event) else settings.LANGUAGES
language = (
self._language_from_user(request, supported)
or self._language_from_cookie(request, supported)
or self._language_from_browser(request, supported)
)
if hasattr(request, 'event') and request.event:
language = language or request.event.locale
translation.activate(language)
request.LANGUAGE_CODE = translation.get_language()
with suppress(pytz.UnknownTimeZoneError):
if request.user.is_authenticated:
tzname = request.user.timezone
elif hasattr(request, 'event') and request.event:
tzname = request.event.timezone
else:
tzname = settings.TIME_ZONE
timezone.activate(pytz.timezone(tzname))
request.timezone = tzname
def __init__(self, begin=None, end=None):
if begin:
self.begin = arrow.Arrow.strptime(begin, '%Y-%m-%d', settings.TIME_ZONE) if begin else arrow.now()
self.begin = self.begin.floor('day').to('UTC').datetime
elif end:
to = arrow.Arrow.strptime(end, '%Y-%m-%d', settings.TIME_ZONE).floor('day').to('UTC').datetime
self.begin = to - timezone.timedelta(days=settings.EVENTS_CALENDAR_PERIOD)
else:
self.begin = arrow.now()
self.begin = self.begin.floor('day').to('UTC').datetime
if end:
self.end = arrow.Arrow.strptime(end, '%Y-%m-%d', settings.TIME_ZONE).floor('day').to('UTC').datetime
else:
self.end = self.begin + timezone.timedelta(days=settings.EVENTS_CALENDAR_PERIOD)
self.events = Event.objects.get_by_dates(begin=self.begin, end=self.end)
def test_event_notifications_task(self):
"""
Test event_notifications_task
"""
event_notifications_task.delay()
self.assertEqual(len(mail.outbox), 2)
event = Event.objects.first()
self.assertEqual(
mail.outbox[0].subject,
settings.EMAIL_SUBJECT_PREFIX + 'Upcoming event - ' + event.title)
self.assertEqual(mail.outbox[1].subject, settings.EMAIL_SUBJECT_PREFIX
+ '??????????? ? ??????????? ??????????')
self.assertNotEqual(event.notified_at, None)
begin = arrow.get(event.begin).to(settings.TIME_ZONE).datetime
sms = Sms.objects.first()
self.assertTrue(begin.strftime('%d.%m.%Y %H:%M') in sms.text)
def event_notifications_task():
events = Event.objects.get_for_notification()
for event in events:
Mailer.mail_managers(
subject='Upcoming event' + ' - ' + event.title,
template='emails/upcoming_event_manager.html',
data={'event': event})
client = event.client
if client.email:
Mailer.mail_user(
subject='??????????? ? ??????????? ??????????',
template='emails/upcoming_event_client.html',
data={'event': event},
email=client.email)
if client.phone:
sender = Sender()
begin = arrow.get(event.begin).to(settings.TIME_ZONE).datetime
sender.send_sms(
'Zdravstvuyte. Napominaju Vam, chto u Vas {} zaplanirovana fotosessija. Aleksandra Vishleva +7(903)735-60-96'.
format(begin.strftime('%d.%m.%Y %H:%M')),
client=client,
send_before=begin - timedelta(hours=6))
event.notified_at = timezone.now()
event.save()
def xformsManifest(request, username, id_string):
xform = get_object_or_404(
XForm, id_string__exact=id_string, user__username__iexact=username)
formlist_user = xform.user
profile, created = \
UserProfile.objects.get_or_create(user=formlist_user)
if profile.require_auth:
authenticator = HttpDigestAuthenticator()
if not authenticator.authenticate(request):
return authenticator.build_challenge_response()
response = render(request, "xformsManifest.xml", {
'host': request.build_absolute_uri().replace(
request.get_full_path(), ''),
'media_files': MetaData.media_upload(xform, download=True)
}, content_type="text/xml; charset=utf-8")
response['X-OpenRosa-Version'] = '1.0'
tz = pytz.timezone(settings.TIME_ZONE)
dt = datetime.now(tz).strftime('%a, %d %b %Y %H:%M:%S %Z')
response['Date'] = dt
return response
def set_asset_user_metadata(instance, user):
"""
Sets Asset uploaded_by, uploaded_at, last_edit_by, last_edit_at and owner.
Called on save by AssetAdmin and FolderAdmin (for AssetInlines).
"""
# on first save...
if not instance.pk:
instance.uploaded_by = user
instance.uploaded_at = datetime.now(timezone(settings.TIME_ZONE))
# on subsequent saves...
else:
instance.last_edit_by = user
instance.last_edit_at = datetime.now(timezone(settings.TIME_ZONE))
# owner cannot be empty...
if not instance.owner:
instance.owner = user
def timezone(self):
"""
Time zone for datetimes stored as naive values in the database.
Returns a tzinfo object or None.
This is only needed when time zone support is enabled and the database
doesn't support time zones. (When the database supports time zones,
the adapter handles aware datetimes so Django doesn't need to.)
"""
if not settings.USE_TZ:
return None
elif self.features.supports_timezones:
return None
elif self.settings_dict['TIME_ZONE'] is None:
return timezone.utc
else:
# Only this branch requires pytz.
return pytz.timezone(self.settings_dict['TIME_ZONE'])
def get_fhir_now(my_now=None):
""" Format a json datetime in xs:datetime format
.now(): 2012-02-17 09:52:35.033232
datetime.datetime.now(pytz.utc).isoformat()
'2012-02-17T11:58:44.789024+00:00'
"""
if my_now:
now_is = my_now
else:
now_is = datetime.now(timezone(settings.TIME_ZONE))
format_now = now_is.isoformat()
return format_now
def timezone(self):
"""
Time zone for datetimes stored as naive values in the database.
Returns a tzinfo object or None.
This is only needed when time zone support is enabled and the database
doesn't support time zones. (When the database supports time zones,
the adapter handles aware datetimes so Django doesn't need to.)
"""
if not settings.USE_TZ:
return None
elif self.features.supports_timezones:
return None
elif self.settings_dict['TIME_ZONE'] is None:
return timezone.utc
else:
return pytz.timezone(self.settings_dict['TIME_ZONE'])
def timezone(self):
"""
Time zone for datetimes stored as naive values in the database.
Returns a tzinfo object or None.
This is only needed when time zone support is enabled and the database
doesn't support time zones. (When the database supports time zones,
the adapter handles aware datetimes so Django doesn't need to.)
"""
if not settings.USE_TZ:
return None
elif self.features.supports_timezones:
return None
elif self.settings_dict['TIME_ZONE'] is None:
return timezone.utc
else:
# Only this branch requires pytz.
return pytz.timezone(self.settings_dict['TIME_ZONE'])
def reading_timestamp_to_datetime(string):
"""
Converts a string containing a timestamp to a timezone aware datetime.
"""
timestamp = re.search(r'(\d{2,2})(\d{2,2})(\d{2,2})(\d{2,2})(\d{2,2})(\d{2,2})([WS])+', string)
meter_timestamp = timezone.datetime(
year=2000 + int(timestamp.group(1)),
month=int(timestamp.group(2)),
day=int(timestamp.group(3)),
hour=int(timestamp.group(4)),
minute=int(timestamp.group(5)),
second=int(timestamp.group(6)),
)
is_dst = timestamp.group(7) == 'S'
local_timezone = pytz.timezone(settings.TIME_ZONE)
return local_timezone.localize(meter_timestamp, is_dst=is_dst).astimezone(pytz.utc)
def get_timestamp(filename):
class GMLHandler(xml.sax.ContentHandler):
timestamp = None
def startElement(self, name, attrs):
if name == "wfs:FeatureCollection":
self.timestamp = attrs['timeStamp']
handler = GMLHandler()
parser = xml.sax.make_parser()
parser.setContentHandler(handler)
parser.parse(filename)
timestamp = iso8601.parse_date(handler.timestamp, default_timezone=None)
return pytz.timezone(settings.TIME_ZONE).localize(timestamp)
def prepare(self, data):
prepped = super(ITSystemEventResource, self).prepare(data)
prepped['event_type'] = data.get_event_type_display()
# Output times as the local timezone.
tz = pytz.timezone(settings.TIME_ZONE)
prepped['start'] = data.start.astimezone(tz)
if data.end:
prepped['end'] = data.end.astimezone(tz)
else:
prepped['end'] = None
if data.duration:
prepped['duration_sec'] = data.duration.seconds
else:
prepped['duration_sec'] = None
if data.it_systems:
prepped['it_systems'] = [i.name for i in data.it_systems.all()]
else:
prepped['it_systems'] = None
if data.locations:
prepped['locations'] = [i.name for i in data.locations.all()]
else:
prepped['locations'] = None
return prepped
def prepare(self, data):
"""Modify the returned object to append the GAL Department value.
"""
prepped = super(DepartmentUserResource, self).prepare(data)
tz = pytz.timezone(settings.TIME_ZONE)
if 'pk' in data:
prepped['gal_department'] = DepartmentUser.objects.get(pk=data['pk']).get_gal_department()
if 'date_updated' in data and data['date_updated']:
prepped['date_updated'] = data['date_updated'].astimezone(tz)
if 'date_ad_updated' in data and data['date_ad_updated']:
prepped['date_ad_updated'] = data['date_ad_updated'].astimezone(tz)
if 'expiry_date' in data and data['expiry_date']:
prepped['expiry_date'] = data['expiry_date'].astimezone(tz)
if data['expiry_date'] < timezone.now():
data['ad_expired'] = True
else:
data['ad_expired'] = False
return prepped
def timezone(self):
"""
Time zone for datetimes stored as naive values in the database.
Returns a tzinfo object or None.
This is only needed when time zone support is enabled and the database
doesn't support time zones. (When the database supports time zones,
the adapter handles aware datetimes so Django doesn't need to.)
"""
if not settings.USE_TZ:
return None
elif self.features.supports_timezones:
return None
elif self.settings_dict['TIME_ZONE'] is None:
return timezone.utc
else:
# Only this branch requires pytz.
return pytz.timezone(self.settings_dict['TIME_ZONE'])
def xformsManifest(request, username, id_string):
xform = get_object_or_404(
XForm, id_string__iexact=id_string, user__username__iexact=username)
formlist_user = xform.user
profile, created = \
UserProfile.objects.get_or_create(user=formlist_user)
if profile.require_auth:
authenticator = HttpDigestAuthenticator()
if not authenticator.authenticate(request):
return authenticator.build_challenge_response()
response = render(request, "xformsManifest.xml", {
'host': request.build_absolute_uri().replace(
request.get_full_path(), ''),
'media_files': MetaData.media_upload(xform, download=True)
}, content_type="text/xml; charset=utf-8")
response['X-OpenRosa-Version'] = '1.0'
tz = pytz.timezone(settings.TIME_ZONE)
dt = datetime.now(tz).strftime('%a, %d %b %Y %H:%M:%S %Z')
response['Date'] = dt
return response
def timezone(self):
"""
Time zone for datetimes stored as naive values in the database.
Returns a tzinfo object or None.
This is only needed when time zone support is enabled and the database
doesn't support time zones. (When the database supports time zones,
the adapter handles aware datetimes so Django doesn't need to.)
"""
if not settings.USE_TZ:
return None
elif self.features.supports_timezones:
return None
elif self.settings_dict['TIME_ZONE'] is None:
return timezone.utc
else:
return pytz.timezone(self.settings_dict['TIME_ZONE'])
def ensure_defaults(self, alias):
"""
Puts the defaults into the settings dictionary for a given connection
where no settings is provided.
"""
try:
conn = self.databases[alias]
except KeyError:
raise ConnectionDoesNotExist("The connection %s doesn't exist" % alias)
conn.setdefault('ATOMIC_REQUESTS', False)
conn.setdefault('AUTOCOMMIT', True)
conn.setdefault('ENGINE', 'django.db.backends.dummy')
if conn['ENGINE'] == 'django.db.backends.' or not conn['ENGINE']:
conn['ENGINE'] = 'django.db.backends.dummy'
conn.setdefault('CONN_MAX_AGE', 0)
conn.setdefault('OPTIONS', {})
conn.setdefault('TIME_ZONE', 'UTC' if settings.USE_TZ else settings.TIME_ZONE)
for setting in ['NAME', 'USER', 'PASSWORD', 'HOST', 'PORT']:
conn.setdefault(setting, '')
def safe_make_aware(value, timezone=None):
"""Safely call Django's make_aware to get aware datetime.
Makes sure DST doesn't cause problems."""
if not timezone:
timezone = settings.TIME_ZONE
return make_aware(value, is_dst=is_dst(timezone))
def test_execution_in_past(self, mock_run):
datawatch.get_all_registered_checks = mock.MagicMock(return_value=[
CheckRunEvery])
scheduler = Scheduler()
scheduler.get_last_executions = mock.MagicMock(return_value={
'django_datawatch.tests.test_scheduler.CheckRunEvery':
datetime.datetime(2016, 1, 1, 0, 0, 0, 0, pytz.timezone(
settings.TIME_ZONE)),
})
scheduler.run_checks()
self.assertTrue(mock_run.called)
def test_execution_in_future(self, mock_run):
datawatch.get_all_registered_checks = mock.MagicMock(return_value=[
CheckRunEvery])
scheduler = Scheduler()
scheduler.get_last_executions = mock.MagicMock(return_value={
'django_datawatch.tests.test_scheduler.CheckRunEvery':
datetime.datetime(2016, 12, 1, 0, 0, 0, 0, pytz.timezone(
settings.TIME_ZONE)),
})
scheduler.run_checks()
self.assertFalse(mock_run.called)
def test_execution_in_future_and_force(self, mock_run):
datawatch.get_all_registered_checks = mock.MagicMock(return_value=[
CheckRunEvery])
scheduler = Scheduler()
scheduler.get_last_executions = mock.MagicMock(return_value={
'django_datawatch.tests.test_scheduler.CheckRunEvery':
datetime.datetime(2016, 12, 1, 0, 0, 0, 0, pytz.timezone(
settings.TIME_ZONE)),
})
scheduler.run_checks(force=True)
self.assertTrue(mock_run.called)
def as_server_datetime(_datetime):
"""Localiza la marca de tiempo en función de la zona de tiempo del servidor"""
SERVERT_PYTZ = pytz.timezone(settings.TIME_ZONE)
return SERVERT_PYTZ.localize(_datetime)
def timezone_name(self):
"""
Name of the time zone of the database connection.
"""
if not settings.USE_TZ:
return settings.TIME_ZONE
elif self.settings_dict['TIME_ZONE'] is None:
return 'UTC'
else:
return self.settings_dict['TIME_ZONE']
def check_settings(self):
if self.settings_dict['TIME_ZONE'] is not None:
if not settings.USE_TZ:
raise ImproperlyConfigured(
"Connection '%s' cannot set TIME_ZONE because USE_TZ is "
"False." % self.alias)
elif self.features.supports_timezones:
raise ImproperlyConfigured(
"Connection '%s' cannot set TIME_ZONE because its engine "
"handles time zones conversions natively." % self.alias)
elif pytz is None:
raise ImproperlyConfigured(
"Connection '%s' cannot set TIME_ZONE because pytz isn't "
"installed." % self.alias)
def get_default_timezone():
"""
Returns the default time zone as a tzinfo instance.
This is the time zone defined by settings.TIME_ZONE.
"""
if isinstance(settings.TIME_ZONE, six.string_types) and pytz is not None:
return pytz.timezone(settings.TIME_ZONE)
else:
# This relies on os.environ['TZ'] being set to settings.TIME_ZONE.
return LocalTimezone()
# This function exists for consistency with get_current_timezone_name
def deactivate():
"""
Unsets the time zone for the current thread.
Django will then use the time zone defined by settings.TIME_ZONE.
"""
if hasattr(_active, "value"):
del _active.value
def _deserialize(self, value, attr, data):
value = int(value)
timezone = pytz.timezone(settings.TIME_ZONE)
return datetime.fromtimestamp(value, timezone)