我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用django.utils.timezone.get_current_timezone_name()。
def get_stations(cls, query): if query.isdigit(): query = 'name:{query} OR number:{query}'.format(query=query) else: # Querying number with a string value raises an error, we remove this field query = 'name:{}'.format(query) req = requests.get(settings.VELIB_API_BASE_URL, params={'apikey': settings.VELIB_API_KEY, 'dataset': 'stations-velib-disponibilites-en-temps-reel', 'fields': 'number,name', 'q': query, #'sort': 'name', Seems to create an error 2016-10-21 'timezone': timezone.get_current_timezone_name()}) if not req.ok: return () data = req.json() if not data.get('nhits', 0): # No matching data found return () return [(item['fields']['number'], item['fields']['name']) for item in data.get('records', [])]
def get_station_infos(cls, station_id): req = requests.get(settings.VELIB_API_BASE_URL, params={'apikey': settings.VELIB_API_KEY, 'dataset': 'stations-velib-disponibilites-en-temps-reel', 'fields': 'name,bike_stands,available_bikes,status', 'q': 'number:"{}"'.format(station_id), 'timezone': timezone.get_current_timezone_name()}) if not req.ok: return None data = req.json() if not data.get('nhits', 0): # No matching data found return None data = data['records'][0]['fields'] return { 'station': data['name'], 'slots': data['bike_stands'], 'bikes': data['available_bikes'], 'status': data['status'] == 'OPEN' }
def get_stations(cls, query): if query.isdigit(): query = 'nom:{query} OR idstation:{query}'.format(query=query) else: # Querying idstation with a string value raises an error, we remove this field query = 'nom:{}'.format(query) req = requests.get(settings.STAR_API_BASE_URL, params={'apikey': settings.STAR_API_KEY, 'dataset': 'vls-stations-etat-tr', 'fields': 'idstation,nom', 'q': query, 'sort': 'nom', 'timezone': timezone.get_current_timezone_name()}) if not req.ok: return () data = req.json() if not data.get('nhits', 0): # No matching data found return () return [(item['fields']['idstation'], item['fields']['nom']) for item in data.get('records', [])]
def get_station_infos(cls, station_id): req = requests.get(settings.STAR_API_BASE_URL, params={'apikey': settings.STAR_API_KEY, 'dataset': 'vls-stations-etat-tr', 'fields': 'nom,nombreemplacementsactuels,nombrevelosdisponibles,etat', 'q': 'idstation:"{}"'.format(station_id), 'timezone': timezone.get_current_timezone_name()}) if not req.ok: return None data = req.json() if not data.get('nhits', 0): # No matching data found return None data = data['records'][0]['fields'] return { 'station': data['nom'], 'slots': data['nombreemplacementsactuels'], 'bikes': data['nombrevelosdisponibles'], 'status': data['etat'] == 'En fonctionnement' }
def setUp(self): self._timezone_backup = timezone.get_current_timezone_name() return super(MiddlewareTests, self).setUp()
def test_timezone_awareness(self): url = settings.LOGIN_REDIRECT_URL mw = middleware.HorizonMiddleware() request = self.factory.get(url) request.session['django_timezone'] = 'America/Chicago' mw.process_request(request) self.assertEqual( timezone.get_current_timezone_name(), 'America/Chicago') request.session['django_timezone'] = 'Europe/Paris' mw.process_request(request) self.assertEqual(timezone.get_current_timezone_name(), 'Europe/Paris') request.session['django_timezone'] = 'UTC' mw.process_request(request) self.assertEqual(timezone.get_current_timezone_name(), 'UTC')
def as_sql(self, compiler, connection): lhs, lhs_params = compiler.compile(self.lhs) tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None sql, tz_params = connection.ops.datetime_cast_date_sql(lhs, tzname) lhs_params.extend(tz_params) return sql, lhs_params
def as_sql(self, compiler, connection): sql, params = compiler.compile(self.lhs) lhs_output_field = self.lhs.output_field if isinstance(lhs_output_field, DateTimeField): tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None sql, tz_params = connection.ops.datetime_extract_sql(self.lookup_name, sql, tzname) params.extend(tz_params) elif isinstance(lhs_output_field, DateField): sql = connection.ops.date_extract_sql(self.lookup_name, sql) elif isinstance(lhs_output_field, TimeField): sql = connection.ops.time_extract_sql(self.lookup_name, sql) else: raise ValueError('DateTransform only valid on Date/Time/DateTimeFields') return sql, params
def tz(request): from django.utils import timezone return {'TIME_ZONE': timezone.get_current_timezone_name()}
def _i18n_cache_key_suffix(request, cache_key): """If necessary, adds the current locale or time zone to the cache key.""" if settings.USE_I18N or settings.USE_L10N: # first check if LocaleMiddleware or another middleware added # LANGUAGE_CODE to request, then fall back to the active language # which in turn can also fall back to settings.LANGUAGE_CODE cache_key += '.%s' % getattr(request, 'LANGUAGE_CODE', get_language()) if settings.USE_TZ: # The datetime module doesn't restrict the output of tzname(). # Windows is known to use non-standard, locale-dependent names. # User-defined tzinfo classes may return absolutely anything. # Hence this paranoid conversion to create a valid cache key. tz_name = force_text(get_current_timezone_name(), errors='ignore') cache_key += '.%s' % tz_name.encode('ascii', 'ignore').decode('ascii').replace(' ', '_') return cache_key
def render(self, context): context[self.variable] = timezone.get_current_timezone_name() return ''
def save(self): data = self.cleaned_data if data.get('register_username') and data.get('register_email') and data.get('register_password'): user = User.objects.create_user(nick=data.get('register_username'), email=data.get('register_email'), password=data.get('register_password'), locale=translation.get_language(), timezone=timezone.get_current_timezone_name()) data['user_id'] = user.pk return data['user_id']
def test_submission_count_for_today_in_form_list(self): self._publish_xls_form_to_project() request = self.factory.get('/', **self.extra) response = self.view(request) self.assertEqual(response.status_code, 200) self.assertIn('submission_count_for_today', response.data[0].keys()) self.assertEqual(response.data[0]['submission_count_for_today'], 0) self.assertEqual(response.data[0]['num_of_submissions'], 0) paths = [os.path.join( self.main_directory, 'fixtures', 'transportation', 'instances_w_uuid', s, s + '.xml') for s in ['transport_2011-07-25_19-05-36']] # instantiate date that is NOT naive; timezone is enabled current_timzone_name = timezone.get_current_timezone_name() current_timezone = pytz.timezone(current_timzone_name) today = datetime.today() current_date = current_timezone.localize( datetime(today.year, today.month, today.day)) self._make_submission(paths[0], forced_submission_time=current_date) self.assertEqual(self.response.status_code, 201) request = self.factory.get('/', **self.extra) response = self.view(request) self.assertEqual(response.status_code, 200) self.assertEqual(response.data[0]['submission_count_for_today'], 1) self.assertEqual(response.data[0]['num_of_submissions'], 1)
def submission_count_for_today(self): current_timzone_name = timezone.get_current_timezone_name() current_timezone = pytz.timezone(current_timzone_name) today = datetime.today() current_date = current_timezone.localize( datetime(today.year, today.month, today.day)) count = self.instances.filter( deleted_at__isnull=True, date_created=current_date).count() return count
def get_tzname(self): # Timezone conversions must happen to the input datetime *before* # applying a function. 2015-12-31 23:00:00 -02:00 is stored in the # database as 2016-01-01 01:00:00 +00:00. Any results should be # based on the input datetime not the stored datetime. tzname = None if settings.USE_TZ: if self.tzinfo is None: tzname = timezone.get_current_timezone_name() else: tzname = timezone._get_timezone_name(self.tzinfo) return tzname
def as_sql(self, compiler, connection): # Cast to date rather than truncate to date. lhs, lhs_params = compiler.compile(self.lhs) tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None sql, tz_params = connection.ops.datetime_cast_date_sql(lhs, tzname) lhs_params.extend(tz_params) return sql, lhs_params
def as_sql(self, compiler, connection): # Cast to date rather than truncate to date. lhs, lhs_params = compiler.compile(self.lhs) tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None sql, tz_params = connection.ops.datetime_cast_time_sql(lhs, tzname) lhs_params.extend(tz_params) return sql, lhs_params
def _placeholder_cache_key(placeholder, lang): cache_key = '%srender_placeholder:%s.%s' % (get_cms_setting("CACHE_PREFIX"), placeholder.pk, str(lang)) if settings.USE_TZ: tz_name = force_text(get_current_timezone_name(), errors='ignore') cache_key += '.%s' % tz_name.encode('ascii', 'ignore').decode('ascii').replace(' ', '_') return cache_key
def _page_cache_key(request): #md5 key of current path cache_key = "%s:%d:%s" % ( get_cms_setting("CACHE_PREFIX"), settings.SITE_ID, hashlib.md5(iri_to_uri(request.get_full_path()).encode('utf-8')).hexdigest() ) if settings.USE_TZ: # The datetime module doesn't restrict the output of tzname(). # Windows is known to use non-standard, locale-dependant names. # User-defined tzinfo classes may return absolutely anything. # Hence this paranoid conversion to create a valid cache key. tz_name = force_text(get_current_timezone_name(), errors='ignore') cache_key += '.%s' % tz_name.encode('ascii', 'ignore').decode('ascii').replace(' ', '_') return cache_key
def test_submission_count_for_today_in_form_list(self): self._publish_xls_form_to_project() request = self.factory.get('/', **self.extra) response = self.view(request) self.assertNotEqual(response.get('Last-Modified'), None) self.assertEqual(response.status_code, 200) self.assertIn('submission_count_for_today', response.data[0].keys()) self.assertEqual(response.data[0]['submission_count_for_today'], 0) self.assertEqual(response.data[0]['num_of_submissions'], 0) paths = [os.path.join( self.main_directory, 'fixtures', 'transportation', 'instances_w_uuid', s, s + '.xml') for s in ['transport_2011-07-25_19-05-36']] # instantiate date that is NOT naive; timezone is enabled current_timzone_name = timezone.get_current_timezone_name() current_timezone = pytz.timezone(current_timzone_name) today = datetime.today() current_date = current_timezone.localize( datetime(today.year, today.month, today.day)) self._make_submission(paths[0], forced_submission_time=current_date) self.assertEqual(self.response.status_code, 201) request = self.factory.get('/', **self.extra) response = self.view(request) self.assertNotEqual(response.get('Last-Modified'), None) self.assertEqual(response.status_code, 200) self.assertEqual(response.data[0]['submission_count_for_today'], 1) self.assertEqual(response.data[0]['num_of_submissions'], 1)
def test_request_processed_user(rf, user): request = rf.get('/') request.user = user TimezoneMiddleware().process_request(request) assert user.timezone == timezone.get_current_timezone_name()
def test_request_processed_default(rf): request = rf.get('/') user = AnonymousUser() request.user = user TimezoneMiddleware().process_request(request) assert settings.TIME_ZONE == timezone.get_current_timezone_name()
def process_lhs(self, compiler, connection, lhs=None): from django.db.models import DateTimeField lhs, params = super(DateLookup, self).process_lhs(compiler, connection, lhs) if isinstance(self.lhs.output_field, DateTimeField): tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None sql, tz_params = connection.ops.datetime_extract_sql(self.extract_type, lhs, tzname) return connection.ops.lookup_cast(self.lookup_name) % sql, tz_params else: return connection.ops.date_extract_sql(self.lookup_name, lhs), []
def track(self, qs): to_date = date.today() start_date = self.get_start_date(qs) if not start_date: return if self.period == Period.LIFETIME: # Intentionally recompute last stat, as we may have computed # that the last time when the day was not over yet. upto_date = start_date while upto_date <= to_date: self.track_lifetime_upto(qs, upto_date) upto_date += timedelta(days=1) elif self.period == Period.DAY: values_fields = ['ts_date'] + self.get_track_values() connection = connections[qs.db] tzname = ( timezone.get_current_timezone_name() if settings.USE_TZ else None) is_datetime = isinstance(qs.model._meta.get_field( self.date_field), models.DateTimeField) if is_datetime: date_sql, tz_params = connection.ops.datetime_cast_date_sql( self.date_field, tzname) vals = qs.extra( select={"ts_date": date_sql}, select_params=tz_params) start_dt = datetime.combine( start_date, time()) - timedelta(days=1) if tzname: start_dt = timezone.make_aware( start_dt, timezone.get_current_timezone()) else: vals = qs.extra(select={"ts_date": self.date_field}) start_dt = start_date vals = vals.filter( **{self.date_field + '__gte': start_dt}).values( *values_fields).order_by().annotate(ts_n=self.aggr_op) # TODO: Bulk create for val in vals: self.statistic_model.objects.record( metric=self.metric, value=val['ts_n'], date=val['ts_date'], period=self.period, **self.get_record_kwargs(val)) else: raise NotImplementedError