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 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 clean_snooze_until(self): data = self.cleaned_data['snooze_until'] usertz = pytz.timezone(timezone.get_current_timezone_name()) snooze_time, snooze_date = None, None # Check if the snooze format is a time delta delta_match = match_delta(data) if delta_match is not None: return delta_match # Check if the snooze format is a time time_match = match_time(data) if time_match is not None: snooze_time = datetime.strptime(time_match[0], '%H:%M:%S') dt = usertz.localize( datetime.combine( self.instance.start_date, snooze_time.time() ) ) if time_match[1] == '': if dt < datetime.now(usertz): dt = dt + timedelta(days=1) if dt > datetime.now(usertz): return dt.astimezone(pytz.timezone('UTC')) msg = 'Please enter a snooze time/date in the future' self._errors['snooze_until'] = self.error_class([msg]) # Check if the snooze format is a date date_match = match_date(data) if date_match is not None: if snooze_time is not None: dt = datetime.combine(date_match[0], snooze_time.time()) else: dt = datetime.combine( date_match[0], self.instance.localised_start().time() ) usertz = pytz.timezone(timezone.get_current_timezone_name()) dt = usertz.localize(dt) if dt > datetime.now(usertz): return dt.astimezone(pytz.timezone('UTC')) msg = 'Please enter a snooze time/date in the future' self._errors['snooze_until'] = self.error_class([msg])
def get_context_data(self, **kwargs): context = super(GameDetailView, self).get_context_data(**kwargs) game = self.object if not game.can_view(self.request.user): raise PermissionDenied() if self.request.GET.get('refresh'): game.refresh(30, True) else: game.refresh(30) context['can_manage'] = game.can_manage(self.request.user) # Player list self.player_list_setup(game, context) game.player_finished_count = \ sum(1 for p in context['players'] if p.finished_turn) game.player_count = len(context['players']) self.log_setup(game, context) context['timezone'] = self.request.session.get('django_timezone') context['timezone_actual'] = timezone.get_current_timezone_name() if game.victory_type > -1: context['victory_info'] = VictoryInfo(game) return context
def get_context_data(self, **kwargs): context = super(TriggerCRUDL.Update, self).get_context_data(**kwargs) if self.get_object().schedule: context['days'] = self.get_object().schedule.explode_bitmask() context['user_tz'] = get_current_timezone_name() context['user_tz_offset'] = int(timezone.localtime(timezone.now()).utcoffset().total_seconds() / 60) return context
def init_review(request, pk): # if request.user.is_authenticated(): # cards = Card.objects.filter(deck=pk) deck = get_object_or_404(Deck, pk=pk) current_step = int(request.GET['step']) limit = int(deck.limit_view_cards) if current_step <= deck.limit_view_cards: cards = Card.objects.filter(deck=pk).order_by('view_date') print('updated date\n') print(timezone.get_current_timezone_name()) print(timezone.get_current_timezone()) print(timezone.now()) print(cards) if cards.count() < limit: if current_step > cards.count(): update_view_date_of_deck(request, pk) return render(request, 'app/init_review.html', {'card': cards[current_step-1], 'deck': deck, 'step': current_step, 'listSize': deck.limit_view_cards if cards.count() > limit else cards.count}) else: return update_view_date_of_deck(request, pk)
def add_episode_file(self, filepath): (tmp, ext) = os.path.splitext(filepath) pathname = os.path.dirname(tmp) filename = os.path.basename(tmp) slug = f'{slugify(filename)}-{get_random_string(10)}' mp3name = slug + ext os.rename(os.path.join(pathname, filename + ext), os.path.join(pathname, mp3name)) pub_date = datetime.now(tz=pytz.timezone(get_current_timezone_name())) with open(os.path.join(pathname, mp3name), "rb") as f: audio = mutagen.mp3.MP3(f, ID3=mutagen.id3.ID3) duration = timedelta(seconds=audio.info.length) # save thumbnail separately try: b = audio.tags.getall('APIC')[0].data image = File(BytesIO(b), name=f'{filename}-thumbnail') except: image = None self.episode_set.create( name=filename, mp3=os.path.join(os.path.basename(pathname), mp3name), slug=slug, pub_date=pub_date, image=image, duration=duration, downloaded=True, updated=True)
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.get_object().schedule: context["days"] = self.get_object().schedule.explode_bitmask() context["user_tz"] = get_current_timezone_name() context["user_tz_offset"] = int(timezone.localtime(timezone.now()).utcoffset().total_seconds() // 60) return context
def get_units_from_timezone() -> int: """Get units from the current timezone.""" name = timezone.get_current_timezone_name() code = get_country_code_from_timezone(name) if code and code in settings.IMPERIAL_UNITS_COUNTRIES: return settings.UNITS_IMPERIAL return settings.UNITS_METRIC
def test_timezone_activation(self): request = self.request_factory.get('/') self.session_middleware.process_request(request) zone = 'America/Montreal' set_session_timezone(request.session, zone) self.middleware.process_request(request) self.assertEqual(timezone.get_current_timezone_name(), zone)
def save(self, *args, **kwargs): self.time_zone = timezone.get_current_timezone_name() if not self.pk: log(user=self.user, action='ADD_USERP', extra={'id': self.id, 'user_name': self.user.username}) else: log(user=self.user, action='UPD_USERP', extra={'id': 0, 'user_name': self.user.username}) return super(UserProfile, self).save(*args, **kwargs)
def __init__(self, *args, **kwargs): self.organizer = kwargs.pop('organizer') self.locales = kwargs.get('locales') self.has_subevents = kwargs.pop('has_subevents') self.user = kwargs.pop('user') kwargs.pop('session') super().__init__(*args, **kwargs) if 'timezone' not in self.initial: self.initial['timezone'] = get_current_timezone_name() self.fields['locale'].choices = [(a, b) for a, b in settings.LANGUAGES if a in self.locales] self.fields['location'].widget.attrs['rows'] = '3' self.fields['location'].widget.attrs['placeholder'] = _( 'Sample Conference Center\nHeidelberg, Germany' ) self.fields['slug'].widget.prefix = build_absolute_uri(self.organizer, 'presale:organizer.index') if self.has_subevents: del self.fields['presale_start'] del self.fields['presale_end'] if self.has_control_rights(self.user, self.organizer): del self.fields['team'] else: self.fields['team'].queryset = self.user.teams.filter(organizer=self.organizer) if not self.organizer.settings.get("event_team_provisioning", True, as_type=bool): self.fields['team'].required = True self.fields['team'].empty_label = None self.fields['team'].initial = 0
def test_timezone_middleware_with_session_key(self): """ Test the middleware with the session key set. """ self.request.session = {TIMEZONE_SESSION_KEY: 'Europe/Paris'} self.assertEqual(None, self.tzmware.process_request(self.request)) self.assertEqual(get_current_timezone_name(), 'Europe/Paris')
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): # 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 _set_timezone(self, request): if request.person.timezone: timezone.activate(request.person.timezone) else: timezone.activate(settings.TIME_ZONE) request.TIME_ZONE = timezone.get_current_timezone_name()
def get_context_data(self, **kwargs): """Update view context.""" context = {} thread = self.object try: user_thread = UserThread.objects.get( user=self.request.user, thread=thread) except ObjectDoesNotExist: pass else: thread.userthread_status = user_thread.status thread.last_read_at = user_thread.last_read_at thread.read = user_thread.read timezone = get_current_timezone_name() context['connectmessages'] = [ message.serializable(timezone=timezone) for message in thread.messages_for_user(self.request.user) ] context['thread'] = thread.serializable(timezone=timezone) # Check to see if the user has seen this message. If not, update the # UserThread to mark the thread as "read" UserThread.objects.filter( thread=thread, user=self.request.user ).update(read=True, last_read_at=now()) return context
def vote_event (request, event_id): event = Event.objects.get(id=event_id) options = event.options_list.all() joptions = [localdata(option) for option in options] user = request.user if not user.is_invited_to(event): raise PermissionDenied FormSet = formset_factory(VoteForm) initial_data = {'form-TOTAL_FORMS': u''+str(len(options)), 'form-INITIAL_FORMS': u''+str(len(options)), 'form-MAX_NUM_FORMS': u'', } for i in xrange(len(options)): initial_data['form-'+str(i)+'-voter']= user.id initial_data['form-'+str(i)+'-interval']= options[i].id pfilled_form = FormSet(initial_data) votes = [ {'option': option, 'form': form} for option, form in zip(joptions, pfilled_form)] return render_to_response('event_vote.html', { 'event_id' : event_id, 'votes' : votes, 'management_form': pfilled_form.management_form, 'username' : request.user.username, 'timezone' : timezone.get_current_timezone_name(), 'timezones': pytz.common_timezones, 'view_name': _('Vote'), 'is_admin' : user.has_perm('admin'), }, context_instance = RequestContext(request))
def get_context_data(self, **kwargs): context = super(GameDetailView, self).get_context_data(**kwargs) game = self.object if not game.can_view(self.request.user): raise PermissionDenied() if self.request.GET.get('refresh'): game.refresh(30, True) else: game.refresh(30) context['can_manage'] = game.can_manage(self.request.user) # Player list self.player_list_setup(game, context) game.player_finished_count = \ sum(1 for p in context['players'] if p.finished_turn) game.player_count = len(context['players']) self.log_setup(game, context) context['timezone'] = self.request.session.get('django_timezone') context['timezone_actual'] = timezone.get_current_timezone_name(); if game.victory_type > -1: context['victory_info'] = VictoryInfo(game) return context
def text_to_time(text): assert text assert text.strip() tz = get_current_timezone_name() try: # return maya.when(text, timezone=tz).datetime(tz) settings = { 'TIMEZONE': tz, 'RETURN_AS_TIMEZONE_AWARE': True, 'TO_TIMEZONE': tz, 'PREFER_DATES_FROM': 'current_period', } log.debug("text: %s", text) return dateparser.parse( text, settings=settings, languages=['pl'], locales=['pl'], date_formats=[ '%Y-%m-%d\t%H:%M', '%Y-%m-%d\t%H:%M:%S', '%d.%m.%Y\t%H:%M', '%-d.%m.%Y\t%H:%M', ], ) except ValueError as ex: raise ValueError(text) from ex
def _update_submission_count_for_today( form_id: int, incr: bool = True, date_created=None): # Track submissions made today 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)).isoformat() date_cache_key = (f"{XFORM_SUBMISSION_COUNT_FOR_DAY_DATE}" f"{form_id}") count_cache_key = (f"{XFORM_SUBMISSION_COUNT_FOR_DAY}{form_id}") if not cache.get(date_cache_key) == current_date: cache.set(date_cache_key, current_date, 86400) if date_created: date_created = current_timezone.localize( datetime(date_created.year, date_created.month, date_created.day) ).isoformat() current_count = cache.get(count_cache_key) if not current_count and incr: cache.set(count_cache_key, 1, 86400) elif incr: cache.incr(count_cache_key) elif current_count and current_count > 0 and date_created == current_date: cache.decr(count_cache_key)
def get_occupation_for_month(asset_id, month, year): result = cache.get_occupation_from_cache(asset_id, month, year) if result is not None: return result try: asset = Asset.objects.get(id=asset_id) except ObjectDoesNotExist: return [] query = """SELECT day, SUM(length) AS total_length FROM (SELECT extract(day FROM reservation_begins) AS day, extract(epoch FROM (reservation_ends - reservation_begins)) AS length FROM assets_reservation WHERE reservation_begins >= (%s) AND reservation_begins < (%s) AND asset_id = (%s)) tab GROUP BY (day) ORDER BY day""" cursor = connection.cursor() cursor.execute("SET TIME ZONE %s;", (timezone.get_current_timezone_name(), )) first_date = str(year) + '-' + str(month) + '-01' last_date = str(year + 1 if month == 12 else year) + '-' + str( (month + 1) % 12) + '-01' cursor.execute(query, (first_date, last_date, asset_id)) occupations = [] limit = asset.max_bookable_slots * asset.capacity * 86400 for i in cursor.fetchall(): occupations.append((i[0], float(i[1]) / limit)) cursor.execute("SET TIME ZONE UTC;") cache.set_occupation_in_cache(asset_id, month, year, occupations) return occupations
def __init__(self, *args, **kwargs): self.organizer = kwargs.pop('organizer') self.locales = kwargs.get('locales') kwargs.pop('user') super().__init__(*args, **kwargs) self.initial['timezone'] = get_current_timezone_name() self.fields['locale'].choices = [(a, b) for a, b in settings.LANGUAGES if a in self.locales]
def prepare_user_in_db(self, nickname_short, password, **kwargs): """Prepares a new User account record. This method only prepares the record model object. The record is saved to the database in the new() method. The account username (nickname_short) must not begin with the Quick List User username prefix. Returns a PADSUser object of the User on success, None on failure. """ new_user = PADSUser() # Generate a new password salt salt = secrets.token_urlsafe(settings['password_salt_bytes']) # Initialise mandatory information new_user.nickname_short = nickname_short new_user.sign_up_date_time = timezone.now() new_user.time_zone = timezone.get_current_timezone_name() new_user.password_hash = self.password_hasher.encode(password, salt) # Initialise optional information new_user.nickname = kwargs.get('nickname', nickname_short) # Set the last login time to a second before sign up date time. # A User has not logged on at all if the last login time is earlier # than the sign up time. new_user.last_login_date_time = timezone.now() - datetime.timedelta( seconds=-1) return new_user
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["user_tz"] = get_current_timezone_name() context["user_tz_offset"] = int( timezone.localtime(timezone.now()).utcoffset().total_seconds() // 60) return context
def as_sql(self, compiler, connection): # Cast to time rather than truncate to time. lhs, lhs_params = compiler.compile(self.lhs) tzname = timezone.get_current_timezone_name( ) if settings.USE_TZ else None sql = connection.ops.datetime_cast_time_sql(lhs, tzname) return sql, lhs_params
def add_request(criteria='', file_type='', requester=None, content_type='', description='', language=None, tz=None): """Add a file request. :param criteria: the criteria that should be used to compose the file :type criteria: str :param file_type: the type of file to generate, e.g. "report-a" or "report-b" :type file_type: str :param requester: the instance of the user performing the requester :param content_type: the content or mime type of the resulting file :type content_type: str :param description: an optional description you can use to remind the user :type description: str :param language: the language to store; will be retrieved from ``django.utils.translation`` if None :type language: str :param tz: the timezone to store; will be retrieved from ``django.utils.timezone`` if None :type tz: str :return: the file request """ if language is None: language = translation.get_language() if tz is None: tz = timezone.get_current_timezone_name() return FileRequest.objects.create(criteria=criteria, file_type=file_type, requester=requester, content_type=content_type, description=description, requested_at=timezone.now(), requester_language=language, requester_timezone=tz)
def get_context_data(self, **kwargs): context = super(TriggerCRUDL.Update, self).get_context_data(**kwargs) if self.get_object().schedule: context['days'] = self.get_object().schedule.explode_bitmask() context['user_tz'] = get_current_timezone_name() context['user_tz_offset'] = int(timezone.localtime(timezone.now()).utcoffset().total_seconds() / 60) return context
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.get_object().schedule: context["days"] = self.get_object().schedule.explode_bitmask() context["user_tz"] = get_current_timezone_name() context["user_tz_offset"] = int(timezone.localtime(timezone.now()).utcoffset().total_seconds() // 60) return context
def get_occupation_for_month(asset_id, month, year): result = cache.get_occupation_from_cache(asset_id, month, year) if result is not None: return result try: asset = Asset.objects.get(id=asset_id) except ObjectDoesNotExist: return [] query = """SELECT day, SUM(length) AS total_length FROM (SELECT extract(day FROM reservation_begins) AS day, extract(epoch FROM (reservation_ends - reservation_begins)) AS length FROM assets_reservation WHERE reservation_begins >= (%s) AND reservation_begins < (%s) AND asset_id = (%s)) tab GROUP BY (day) ORDER BY day""" cursor = connection.cursor() cursor.execute("SET TIME ZONE %s;", (timezone.get_current_timezone_name(), )) first_date = str(year) + '-' + str(month) + '-01' last_date = str(year + 1 if month == 12 else year) + '-' + str((month + 1) % 12) + '-01' cursor.execute(query, (first_date, last_date, asset_id)) occupations = [] limit = asset.max_bookable_slots * asset.capacity * 86400 for i in cursor.fetchall(): occupations.append((i[0], float(i[1]) / limit)) cursor.execute("SET TIME ZONE UTC;") cache.set_occupation_in_cache(asset_id, month, year, occupations) return occupations
def test_middleware_sets_timezone_for_guest(self): """Middleware sets ip from remote_addr header""" request = MockRequest(MockGuest()) TimezoneMiddleware().process_request(request) self.assertEqual(timezone.get_current_timezone_name().lower(), settings.default_timezone)
def test_middleware_sets_timezone_for_authenticated(self): """Middleware sets ip from forwarded_for header""" request = MockRequest(MockAuthenticated()) TimezoneMiddleware().process_request(request) self.assertEqual(timezone.get_current_timezone_name(), MockAuthenticated.timezone)
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 dataframe(self) -> pd.DataFrame: """ SQLクエリとDataFrame変換コストがあるためcached_propertyを利用 期間別処理が必要なためindexに設定し、timezoneがUTCになるため変換する """ df = self.model.objects.to_dataframe(index=self.date_field) return df.tz_convert(timezone.get_current_timezone_name())
def __init__(self, attrs=None, format=None): attrs = attrs or {} attrs['data-widget-positioning'] = '{"horizontal": "right", "vertical": "bottom"}' attrs['data-format'] = self._moment_format(format or formats.get_format(self.format_key)[0]) if settings.USE_TZ: attrs['data-time-zone'] = timezone.get_current_timezone_name() super(DateTimeMixin, self).__init__(attrs=attrs, format=format)
def get_context_data(self, **kwargs): """Update view context.""" context = {} thread = self.object try: user_thread = UserThread.objects.get(user=self.request.user, thread=thread) except ObjectDoesNotExist: pass else: thread.userthread_status = user_thread.status thread.last_read_at = user_thread.last_read_at thread.read = user_thread.read timezone = get_current_timezone_name() context['connectmessages'] = [ message.serializable(timezone=timezone) for message in thread.messages_for_user(self.request.user) ] context['thread'] = thread.serializable(timezone=timezone) # Check to see if the user has seen this message. If not, update the # UserThread to mark the thread as "read" UserThread.objects.filter( thread=thread, user=self.request.user).update(read=True, last_read_at=now()) return context
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 test_process_request_with_tz_cookie(self): user_tz = 'Asia/Vladivostok' self.request.COOKIES = {'USER_TZ': user_tz} self.middleware.process_request(self.request) active_tz = timezone.get_current_timezone_name() self.assertEqual(active_tz, user_tz)
def handler500(request): message = _("500! Something went wrong with our server. We are sorry!") return render(request, 'errors.html', {'message': message, 'username' : request.user.username, 'timezone' : timezone.get_current_timezone_name(), 'timezones': pytz.common_timezones, 'view_name' : _('500'), 'is_admin' : request.user.has_perm('admin'),})
def get_timezone_from_ip(ip): data = GeoIP().city(ip) or None _timezone = pytz.timezone(timezone.get_current_timezone_name()) if data: _timezone = GeoIPC.time_zone_by_country_and_region( data.get('country_code'), data.get('region')) _timezone = pytz.timezone(_timezone) return _timezone.zone
def as_postgresql(self, compiler, connection): lhs, lhs_params = compiler.compile(self.lhs) if settings.USE_TZ: lhs = "%s AT TIME ZONE %%s" % lhs tzname = timezone.get_current_timezone_name() lhs_params.append(tzname) sql = "(%s)::time" % lhs return sql, lhs_params
def handler404(request): message = _("404! The page you requested was not found!") return render(request, 'errors.html', {'message': message, 'username' : request.user.username, 'timezone' : timezone.get_current_timezone_name(), 'timezones': pytz.common_timezones, 'view_name' : _('404'), 'is_admin' : request.user.has_perm('admin'),})
def get_context_data(self, **kwargs): org = self.get_object().org context = super().get_context_data(**kwargs) context["days"] = self.get_object().repeat_days_of_week or "" context["user_tz"] = get_current_timezone_name() context["user_tz_offset"] = int(timezone.now().astimezone( org.timezone).utcoffset().total_seconds() // 60) return context
def as_mysql(self, compiler, connection): lhs, lhs_params = compiler.compile(self.lhs) if settings.USE_TZ: lhs = "CONVERT_TZ(%s, 'UTC', %%s)" % lhs tzname = timezone.get_current_timezone_name() lhs_params.append(tzname) sql = "TIME(%s)" % lhs return sql, lhs_params
def time_zone_context(self): context = {} # Duplicate the functionality of django.template.context_processors.tz. context["TIME_ZONE"] = timezone.get_current_timezone_name() # Add a list of time zones to the context. context["TIME_ZONES"] = pytz.common_timezones return context
def test_set_timezone(self): "Ensure time zone is correct before, during and after a set request" self.assertEqual( timezone.get_current_timezone_name(), timezone.get_default_timezone_name() ) data = { "timezone": "Australia/Sydney", } self.post("set-timezone", data=data, follow=True) self.assertResponseContains( '<option value="Australia/Sydney" selected>Sydney</option>' ) self.assertEqual( timezone.get_current_timezone_name(), timezone.get_default_timezone_name() )
def handler403(request): message = _("403! You Don't have permission to access this page!") return render(request, 'errors.html', {'message': message, 'username' : request.user.username, 'timezone' : timezone.get_current_timezone_name(), 'timezones': pytz.common_timezones, 'view_name' : _('403'), 'is_admin' : request.user.has_perm('admin'),})
def get_cache_key(self, lang): cache_key = '%srender_placeholder:%s.%s' % ( get_cms_setting("CACHE_PREFIX"), self.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 get_context_data(self, **kwargs): context = super(TriggerCRUDL.Schedule, self).get_context_data(**kwargs) context['user_tz'] = get_current_timezone_name() context['user_tz_offset'] = int( timezone.localtime(timezone.now()).utcoffset().total_seconds() / 60) return context
def dispatch(self, request, *args, **kwargs): self.form = forms.SearchForm(request.GET) self.page_base_url = request.path self.timezone = get_current_timezone_name() if request.is_ajax(): self.show_timeline = False self.template_name = 'logs/log_display.html' return super(LogViewer, self).dispatch(request, *args, **kwargs)
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 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 clean_date_time(self): """ Converts date_time field from localized time zone to utc. """ date_time = self.cleaned_data['date_time'] user_tz = pytz.timezone(get_current_timezone_name()) date_time = user_tz.localize(date_time) return date_time.astimezone(pytz.utc)
def process_lhs(self, qn, connection, lhs=None): from django.db.models import DateTimeField lhs, params = super(DateLookup, self).process_lhs(qn, 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 test_timezone_setting(regular_user): get_default_shop() # Create a shop mw = ShoopFrontMiddleware() request = get_unprocessed_request() request.user = regular_user some_tz = ('US/Hawaii' if settings.TIME_ZONE == 'UTC' else 'UTC') person = shoop.core.models.get_person_contact(regular_user) person.timezone = some_tz person.save() assert timezone.get_current_timezone_name() != some_tz mw.process_request(request) assert timezone.get_current_timezone_name() == some_tz
def build_tweet(data): return { 'id': data.id_str, 'created_at': pytz\ .timezone(timezone.get_current_timezone_name())\ .localize(data.created_at), 'author': build_user(data.author), 'favorite_count': data.favorite_count, 'text': data.text }
def _i18n_cache_key_suffix(request, cache_key): """If necessary, add 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: cache_key += '.%s' % get_current_timezone_name() return cache_key