def test_today_timezone(self, mock_now): """Values are normalized to local time correctly.""" d = datetime.datetime(2012, 1, 2, 23, 10, tzinfo=denver) with timezone.override(denver): assert serializers.naturaldatetime(d) == u"11:10pm" with timezone.override(timezone.utc): assert serializers.naturaldatetime(d) == u"6:10am"
def test_utc_date_and_local_date_filters(self): u""" Tests ``datetime|utc_date`` and ``datetime|local_date`` filter. The filters are tested with datetimes in UTC, in local timezone and in some other explicitly set timezone. The filters are also tested with points in time respresenting different date in local timezone than in UTC. """ with timezone.override(u'Europe/Bratislava'): # UTC +1 # 2014-12-11 00:20:00 in Europe/Bratislava == 2014-12-10 23:20:00 UTC; Still yesterday in UTC utc = utc_datetime_from_local(2014, 12, 11, 0, 20, 0) local = local_datetime_from_local(2014, 12, 11, 0, 20, 0) rendered = self._render( u'{% load utc_date local_date from poleno.utils %}' u'({{ utc|utc_date|date:"Y-m-d" }})' u'({{ local|utc_date|date:"Y-m-d" }})' u'({{ utc|local_date|date:"Y-m-d" }})' u'({{ local|local_date|date:"Y-m-d" }})' u'', utc=utc, local=local) self.assertEqual(rendered, u'(2014-12-10)(2014-12-10)(2014-12-11)(2014-12-11)') # 2014-12-11 10:20:00 in Europe/Bratislava == 2014-12-11 09:20:00 UTC; The same day in UTC utc = utc_datetime_from_local(2014, 12, 11, 10, 20, 0) local = local_datetime_from_local(2014, 12, 11, 10, 20, 0) rendered = self._render( u'{% load utc_date local_date from poleno.utils %}' u'({{ utc|utc_date|date:"Y-m-d" }})' u'({{ local|utc_date|date:"Y-m-d" }})' u'({{ utc|local_date|date:"Y-m-d" }})' u'({{ local|local_date|date:"Y-m-d" }})' u'', utc=utc, local=local) self.assertEqual(rendered, u'(2014-12-11)(2014-12-11)(2014-12-11)(2014-12-11)') with timezone.override(u'America/Montreal'): # UTC -5 # 2014-12-11 22:20:00 in America/Montreal == 2014-12-12 03:20:00 UTC; Already tomorrow in UTC utc = utc_datetime_from_local(2014, 12, 11, 22, 20, 0) local = local_datetime_from_local(2014, 12, 11, 22, 20, 0) rendered = self._render( u'{% load utc_date local_date from poleno.utils %}' u'({{ utc|utc_date|date:"Y-m-d" }})' u'({{ local|utc_date|date:"Y-m-d" }})' u'({{ utc|local_date|date:"Y-m-d" }})' u'({{ local|local_date|date:"Y-m-d" }})' u'', utc=utc, local=local) self.assertEqual(rendered, u'(2014-12-12)(2014-12-12)(2014-12-11)(2014-12-11)') # 2014-12-11 04:20:00 in Europe/Bratislava == 2014-12-11 03:20:00 UTC == 2014-12-10 22:20:00 in America/Montreal with timezone.override(u'Europe/Bratislava'): # UTC +1 other = local_datetime_from_local(2014, 12, 11, 4, 20, 0) other_tz = timezone.get_current_timezone() rendered = self._render( u'{% load utc_date local_date from poleno.utils %}' u'({{ other|utc_date|date:"Y-m-d" }})' u'({{ other|local_date|date:"Y-m-d" }})' u'({{ other|local_date:other_tz|date:"Y-m-d" }})' u'', other=other, other_tz=other_tz) self.assertEqual(rendered, u'(2014-12-11)(2014-12-10)(2014-12-11)')
def test_json_tz(self): view = SuperView() context_0 = {"date": parse_datetime("2012-02-21 10:28:45").replace(tzinfo=utc)} with override(pytz.timezone("Australia/Sydney")): response = view.render_json(context_0) jdata = json.loads(response.content) self.assertEqual(jdata["date"], "2012-02-21T21:28:45+11:00") with override(pytz.timezone("Europe/Madrid")): response = view.render_json(context_0) jdata = json.loads(response.content) self.assertEqual(jdata["date"], "2012-02-21T11:28:45+01:00")
def test_get_current_timezone_templatetag(self): """ Test the {% get_current_timezone %} templatetag. """ tpl = Template("{% load tz %}{% get_current_timezone as time_zone %}{{ time_zone }}") self.assertEqual(tpl.render(Context()), "Africa/Nairobi" if pytz else "EAT") with timezone.override(UTC): self.assertEqual(tpl.render(Context()), "UTC") tpl = Template("{% load tz %}{% timezone tz %}{% get_current_timezone as time_zone %}{% endtimezone %}{{ time_zone }}") self.assertEqual(tpl.render(Context({'tz': ICT})), "+0700") with timezone.override(UTC): self.assertEqual(tpl.render(Context({'tz': ICT})), "+0700")
def plot_useranalytics(request): """ Creates a PNG image containing different plots for analzing the performance of individual users over time. """ time_zone = pytz.utc userid = request.GET.get('userid', -1) project_id = request.GET.get('project_id', None) project = get_object_or_404(Project, pk=project_id) if project_id else None all_writes = request.GET.get('all_writes', 'false') == 'true' maxInactivity = int(request.GET.get('max_inactivity', 3)) # Get the start date for the query, defaulting to 7 days ago. start_date = request.GET.get('start', None) if start_date: start_date = dateparser.parse(start_date) else: with timezone.override(time_zone): start_date = timezone.now() - timedelta(7) start_date = datetime(start_date.year, start_date.month, start_date.day, tzinfo=time_zone) # Get the end date for the query, defaulting to now. end_date = request.GET.get('end', None) if end_date: end_date = dateparser.parse(end_date) else: with timezone.override(time_zone): end_date = timezone.now() # The API is inclusive and should return stats for the end date as # well. The actual query is easier with an exclusive end and therefore # the end date is set to the beginning of the next day. end_date = end_date + timedelta(days=1) end_date = datetime(end_date.year, end_date.month, end_date.day, tzinfo=time_zone) if request.user.is_superuser or \ project and request.user.has_perm('can_administer', project): f = generateReport( userid, project_id, maxInactivity, start_date, end_date, all_writes ) else: f = generateErrorImage('You lack permissions to view this report.') canvas = FigureCanvasAgg( f ) response = HttpResponse(content_type='image/png') canvas.print_png(response) return response
def plot_useranalytics(request, project_id): """ Creates an SVG image containing different plots for analzing the performance of individual users over time. """ time_zone = pytz.utc userid = request.GET.get('userid', None) if not (userid and userid.strip()): raise ValueError("Need user ID") project = get_object_or_404(Project, pk=project_id) if project_id else None all_writes = get_request_bool(request.GET, 'all_writes', False) maxInactivity = int(request.GET.get('max_inactivity', 3)) # Get the start date for the query, defaulting to 7 days ago. start_date = request.GET.get('start', None) if start_date: start_date = dateparser.parse(start_date) start_date = time_zone.localize(start_date) else: with timezone.override(time_zone): start_date = timezone.now() - timedelta(7) # Get the end date for the query, defaulting to now. end_date = request.GET.get('end', None) if end_date: end_date = dateparser.parse(end_date) end_date = time_zone.localize(end_date) else: with timezone.override(time_zone): end_date = timezone.now() # The API is inclusive and should return stats for the end date as # well. The actual query is easier with an exclusive end and therefore # the end date is set to the beginning of the next day. end_date = end_date + timedelta(days=1) if request.user.is_superuser or \ project and request.user.has_perm('can_browse', project): f = generateReport( userid, project_id, maxInactivity, start_date, end_date, all_writes ) else: f = generateErrorImage('You lack permissions to view this report.') # Use raw text rather than SVG fonts or pathing. plt.rcParams['svg.fonttype'] = 'none' buf = io.BytesIO() plt.savefig(buf, format='svg') return HttpResponse(buf.getvalue(), content_type='image/svg+xml')
def _test_file_time_getter_tz_handling_off(self, getter): # Django's TZ (and hence the system TZ) is set to Africa/Algiers which # is UTC+1 and has no DST change. We can set the Django TZ to something # else so that UTC, Django's TIME_ZONE, and the system timezone are all # different. now_in_algiers = timezone.make_aware(datetime.now()) with timezone.override(timezone.get_fixed_timezone(-300)): # At this point the system TZ is +1 and the Django TZ # is -5. self.assertFalse(self.storage.exists('test.file.tz.off')) f = ContentFile('custom contents') f_name = self.storage.save('test.file.tz.off', f) self.addCleanup(self.storage.delete, f_name) dt = getter(f_name) # dt should be naive, in system (+1) TZ self.assertTrue(timezone.is_naive(dt)) # The three timezones are indeed distinct. naive_now = datetime.now() algiers_offset = now_in_algiers.tzinfo.utcoffset(naive_now) django_offset = timezone.get_current_timezone().utcoffset(naive_now) utc_offset = timezone.utc.utcoffset(naive_now) self.assertGreater(algiers_offset, utc_offset) self.assertLess(django_offset, utc_offset) # dt and naive_now should be the same effective time. self.assertLess(abs(dt - naive_now), timedelta(seconds=2)) # If we convert dt to an aware object using the Algiers # timezone then it should be the same effective time to # now_in_algiers. _dt = timezone.make_aware(dt, now_in_algiers.tzinfo) self.assertLess(abs(_dt - now_in_algiers), timedelta(seconds=2))
def render_node(node, context, options, args, kwargs): if not options: return node.render(context) safe = options['safe'] application = options['application'] timezone = options['timezone'] language = options['language'] localized = options['localized'] # formats = options['formats'] context.autoescape = not safe context.current_app = application context.use_tz = bool(timezone) context.use_i18n = bool(language) context.use_l10n = bool(localized) if language: tr.activate(language[0]) if localized: pass # TODO with tz.override(timezone) if timezone else noop: return node.render(context)
def list(self, request, *args, **kwargs): data = TransmissionForm(request.query_params) if not data.is_valid(): raise DRFValidationError(data.errors) requested_timezone = data.cleaned_data.get('timezone') after = data.cleaned_data['after'] before = data.cleaned_data['before'] tz = requested_timezone or pytz.utc after_date = tz.localize(datetime.datetime.combine(after, datetime.time())) before_date = tz.localize(datetime.datetime.combine(before, datetime.time(23, 59, 59))) # Apply filters to the queryset schedules = self.filter_queryset(self.get_queryset()) # Filter by active calendar if that filter was not provided if not data.cleaned_data.get('calendar'): schedules = schedules.filter(calendar__is_active=True) transmissions = Transmission.between( after_date, before_date, schedules=schedules ) serializer = self.get_serializer(transmissions, many=True) with override(timezone=tz): return Response(serializer.data)
def _test_file_time_getter_tz_handling_on(self, getter): # Django's TZ (and hence the system TZ) is set to Africa/Algiers which # is UTC+1 and has no DST change. We can set the Django TZ to something # else so that UTC, Django's TIME_ZONE, and the system timezone are all # different. now_in_algiers = timezone.make_aware(datetime.now()) # Use a fixed offset timezone so we don't need pytz. with timezone.override(timezone.get_fixed_timezone(-300)): # At this point the system TZ is +1 and the Django TZ # is -5. The following will be aware in UTC. now = timezone.now() self.assertFalse(self.storage.exists('test.file.tz.on')) f = ContentFile('custom contents') f_name = self.storage.save('test.file.tz.on', f) self.addCleanup(self.storage.delete, f_name) dt = getter(f_name) # dt should be aware, in UTC self.assertTrue(timezone.is_aware(dt)) self.assertEqual(now.tzname(), dt.tzname()) # Check that the three timezones are indeed distinct. naive_now = datetime.now() algiers_offset = now_in_algiers.tzinfo.utcoffset(naive_now) django_offset = timezone.get_current_timezone().utcoffset(naive_now) utc_offset = timezone.utc.utcoffset(naive_now) self.assertGreater(algiers_offset, utc_offset) self.assertLess(django_offset, utc_offset) # dt and now should be the same effective time. self.assertLess(abs(dt - now), timedelta(seconds=2))
def test_change_readonly_in_other_timezone(self): Timestamp.objects.create() # re-fetch the object for backends that lose microseconds (MySQL) t = Timestamp.objects.get() with timezone.override(ICT): response = self.client.get(reverse('admin:timezones_timestamp_change', args=(t.pk,))) self.assertContains(response, t.created.astimezone(ICT).isoformat())
def test_localdate(self): naive = datetime.datetime(2015, 1, 1, 0, 0, 1) with self.assertRaisesMessage(ValueError, 'localtime() cannot be applied to a naive datetime'): timezone.localdate(naive) with self.assertRaisesMessage(ValueError, 'localtime() cannot be applied to a naive datetime'): timezone.localdate(naive, timezone=EAT) aware = datetime.datetime(2015, 1, 1, 0, 0, 1, tzinfo=ICT) self.assertEqual(timezone.localdate(aware, timezone=EAT), datetime.date(2014, 12, 31)) with timezone.override(EAT): self.assertEqual(timezone.localdate(aware), datetime.date(2014, 12, 31)) with mock.patch('django.utils.timezone.now', return_value=aware): self.assertEqual(timezone.localdate(timezone=EAT), datetime.date(2014, 12, 31)) with timezone.override(EAT): self.assertEqual(timezone.localdate(), datetime.date(2014, 12, 31))
def test_extract_func_with_timezone(self): start_datetime = microsecond_support(datetime(2015, 6, 15, 23, 30, 1, 321)) end_datetime = microsecond_support(datetime(2015, 6, 16, 13, 11, 27, 123)) start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) melb = pytz.timezone('Australia/Melbourne') qs = DTModel.objects.annotate( day=Extract('start_datetime', 'day'), day_melb=Extract('start_datetime', 'day', tzinfo=melb), weekday=ExtractWeekDay('start_datetime'), weekday_melb=ExtractWeekDay('start_datetime', tzinfo=melb), hour=ExtractHour('start_datetime'), hour_melb=ExtractHour('start_datetime', tzinfo=melb), ).order_by('start_datetime') utc_model = qs.get() self.assertEqual(utc_model.day, 15) self.assertEqual(utc_model.day_melb, 16) self.assertEqual(utc_model.weekday, 2) self.assertEqual(utc_model.weekday_melb, 3) self.assertEqual(utc_model.hour, 23) self.assertEqual(utc_model.hour_melb, 9) with timezone.override(melb): melb_model = qs.get() self.assertEqual(melb_model.day, 16) self.assertEqual(melb_model.day_melb, 16) self.assertEqual(melb_model.weekday, 3) self.assertEqual(melb_model.weekday_melb, 3) self.assertEqual(melb_model.hour, 9) self.assertEqual(melb_model.hour_melb, 9)
def discount_form(request, *args, **kwargs): event = get_object_or_404(Event.objects.select_related('organization'), slug=kwargs['event_slug'], organization__slug=kwargs['organization_slug']) if not event.editable_by(request.user): raise Http404 if 'pk' in kwargs: discount = get_object_or_404(Discount, pk=kwargs['pk']) else: discount = None if request.method == 'POST': form = DiscountForm(event, request.POST, instance=discount) with timezone.override(event.timezone): # Clean as the event's timezone - datetimes # input correctly. if form.is_valid(): form.save() url = reverse('brambling_discount_list', kwargs={'event_slug': event.slug, 'organization_slug': event.organization.slug}) return HttpResponseRedirect(url) else: form = DiscountForm(event, instance=discount) context = { 'event': event, 'discount': form.instance, 'discount_form': form, 'cart': None, 'event_admin_nav': get_event_admin_nav(event, request), } return render_to_response('brambling/event/organizer/discount_form.html', context, context_instance=RequestContext(request))
def clean_timezone(self): cleantimezone = self.cleaned_data['timezone'] try: with timezone.override(cleantimezone): return cleantimezone except: raise forms.ValidationError(INVALID_TIMEZONE_ERROR)
def test_form_with_ambiguous_time(self): with timezone.override(pytz.timezone('Europe/Paris')): form = EventForm({'dt': u'2011-10-30 02:30:00'}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['dt'], [u"2011-10-30 02:30:00 couldn't be interpreted in time zone " u"Europe/Paris; it may be ambiguous or it may not exist."])
def test_date_and_time_template_filters_honor_localtime(self): tpl = Template( "{% load tz %}{% localtime off %}{{ dt|date:'Y-m-d' }} at {{ dt|time:'H:i:s' }}{% endlocaltime %}" ) ctx = Context({"dt": datetime.datetime(2011, 9, 1, 20, 20, 20, tzinfo=UTC)}) self.assertEqual(tpl.render(ctx), "2011-09-01 at 20:20:20") with timezone.override(ICT): self.assertEqual(tpl.render(ctx), "2011-09-01 at 20:20:20")
def test_localtime(self): now = datetime.datetime.utcnow().replace(tzinfo=timezone.utc) local_tz = timezone.LocalTimezone() with timezone.override(local_tz): local_now = timezone.localtime(now) self.assertEqual(local_now.tzinfo, local_tz) local_now = timezone.localtime(now, timezone=local_tz) self.assertEqual(local_now.tzinfo, local_tz)
def reset(request): with timezone.override("US/Eastern"): the_dripper.simulated_time = timezone.make_aware(dt.datetime(2016, 4, 5, 0, 0)) dripper_time = PlantSetting.objects.last() dripper_time.dripper_start = the_dripper.simulated_time dripper_time.save() the_dripper.clear_targets() HPVATM.objects.all().delete() return redirect('dripper:status')
def get_time_with_timezone(plant_settings): """ Gets the current time, making it timezone aware and in US/Eastern. :param plant_settings: The most recent instance of the plant settings. :return: TZ aware datetime object """ with timezone.override("US/Eastern"): return timezone.localtime(plant_settings.dripper_start)
def test_get_current_timezone_templatetag_with_pytz(self): """ Test the {% get_current_timezone %} templatetag with pytz. """ tpl = Template("{% load tz %}{% get_current_timezone as time_zone %}{{ time_zone }}") with timezone.override(pytz.timezone('Europe/Paris')): self.assertEqual(tpl.render(Context()), "Europe/Paris") tpl = Template("{% load tz %}{% timezone 'Europe/Paris' %}{% get_current_timezone as time_zone %}{% endtimezone %}{{ time_zone }}") self.assertEqual(tpl.render(Context()), "Europe/Paris")
def test_clean_value_with_timestamp_string_no_timezone(self): """Testing DateTimeFieldType.clean_value with timestamp string without timezone offset """ pst = pytz.timezone('US/Pacific') with timezone.override(pst): self.assertEqual( self.field_type.clean_value('2018-02-20T13:42:00'), pst.localize(datetime(2018, 2, 20, 13, 42, 0)))
def test_clean_value_with_naive_datetime(self): """Testing DateTimeFieldType.clean_value with naive datetime""" dt = datetime(2018, 2, 20, 13, 42, 0) self.assertTrue(timezone.is_naive(dt)) pst = pytz.timezone('US/Pacific') with timezone.override(pst): self.assertEqual(self.field_type.clean_value(dt), pst.localize(dt))
def test_form_with_non_existent_time(self): with timezone.override(pytz.timezone("Europe/Paris")): form = EventForm({"dt": u"2011-03-27 02:30:00"}) self.assertFalse(form.is_valid()) self.assertEqual( form.errors["dt"], [ u"2011-03-27 02:30:00 couldn't be interpreted in time zone " u"Europe/Paris; it may be ambiguous or it may not exist." ], )
def test_clean_value_with_timestamp_string_ambiguous(self): """Testing DateTimeFieldType.clean_value with timestamp string with ambiguous time """ with timezone.override(pytz.timezone('America/Chicago')): expected_message = ( 'This timestamp needs a UTC offset to avoid being ambiguous ' 'due to daylight savings time changes' ) with self.assertRaisesMessage(ValidationError, expected_message): self.field_type.clean_value('2016-11-06T01:05:59')
def test_timezone_change(self, monkeypatch): warsaw = pytz.timezone("Europe/Warsaw") berlin = pytz.timezone("Europe/Berlin") def check_tz(): assert timezone.get_current_timezone() == warsaw with timezone.override(berlin): mixin = mixins.LocalizationMixin(timezone=warsaw) monkeypatch.setattr(mixin, 'get_message', check_tz) mixin.build() assert timezone.get_current_timezone() == berlin
def export(event: str, fileid: str, provider: str, form_data: Dict[str, Any]) -> None: event = Event.objects.get(id=event) file = CachedFile.objects.get(id=fileid) with language(event.settings.locale), override(event.settings.timezone): responses = register_data_exporters.send(event) for receiver, response in responses: ex = response(event) if ex.identifier == provider: file.filename, file.type, data = ex.render(form_data) file.file.save(cachedfile_name(file, file.filename), ContentFile(data)) file.save() return file.pk
def convert_timestamp(timestamp): """Convenience method to convert (possible naive) timestamps.""" if timestamp is None: return None if isinstance(timestamp, str): timestamp = parse_datetime(timestamp) with override('America/Los_Angeles'): if not is_aware(timestamp): timestamp = make_aware(timestamp) return timestamp
def test_summary_email_dates_printed_correctly(self): mail.outbox = [] with timezone.override(timezone.utc), freeze_time( datetime.datetime(2018, 8, 19)): # Sunday group = GroupFactory() self.make_activity_in_group(group) from_date, to_date = calculate_group_summary_dates(group) context = prepare_group_summary_data(group, from_date, to_date) emails = prepare_group_summary_emails(group, context) self.assertGreater(len(emails), 0) email = emails[0] expected_format = 'Sunday, August 12, 2018 to Saturday, August 18, 2018' self.assertIn(expected_format, email.body)
def get_grace_start(self): """ Return the datetime when grace period starts. """ # The common case, grace starts after timeout if self.kind == "simple": return self.last_ping + self.timeout # The complex case, next ping is expected based on cron schedule with timezone.override(self.tz): last_naive = timezone.make_naive(self.last_ping) it = croniter(self.schedule, last_naive) next_naive = it.get_next(datetime) return timezone.make_aware(next_naive, is_dst=False)
def load_raw_data(): # process generator file. CSV has headers. # each row is a dict. with timezone.override('US/Pacific'): for row in read_csv_generator(plant_activty_csv, headers=True): created_row = PlantActivityModel.objects.create( UNIT_NUM=row['UNIT_NUM'], UNIT_COMPLETED_DEPT=row['UNIT_COMPLETED_DEPT'], UNIT_LOADED_TIME=process_date(row['UNIT_LOADED_TIME']), ) created_row.save() print("LOADED plant Row")
def get_grace_start(self): """ Return the datetime when grace period starts. """ # The common case, grace starts after timeout if self.kind == "simple": return self.last_ping + self.timeout # The complex case, next ping is expected based on cron schedule with timezone.override(self.tz): last_naive = timezone.make_naive(self.last_ping) it = croniter(self.schedule, last_naive) next_naive = it.get_next(datetime) return timezone.make_aware(next_naive, is_dst=True)
def multiexport(self, organizer: Organizer, user: User, device: int, token: int, fileid: str, provider: str, form_data: Dict[str, Any]) -> None: if device: device = Device.objects.get(pk=device) if token: device = TeamAPIToken.objects.get(pk=token) allowed_events = (device or token or user).get_events_with_permission('can_view_orders') def set_progress(val): if not self.request.called_directly: self.update_state(state='PROGRESS', meta={'value': val}) file = CachedFile.objects.get(id=fileid) if user: locale = user.locale timezone = user.timezone region = None # todo: add to user? else: e = allowed_events.first() if e: locale = e.settings.locale timezone = e.settings.timezone region = e.settings.region else: locale = settings.LANGUAGE_CODE timezone = settings.TIME_ZONE region = None with language(locale, region), override(timezone): if isinstance(form_data['events'][0], str): events = allowed_events.filter(slug__in=form_data.get('events'), organizer=organizer) else: events = allowed_events.filter(pk__in=form_data.get('events')) responses = register_multievent_data_exporters.send(organizer) for receiver, response in responses: if not response: continue ex = response(events, set_progress) if ex.identifier == provider: d = ex.render(form_data) if d is None: raise ExportError( gettext('Your export did not contain any data.')) file.filename, file.type, data = d file.file.save(cachedfile_name(file, file.filename), ContentFile(data)) file.save() return file.pk
def calculate_group_summary_dates(group): with timezone.override(group.timezone): tz = get_current_timezone() # midnight last night in the groups local timezone midnight = tz.localize(timezone.now().replace(tzinfo=None, hour=0, minute=0, second=0, microsecond=0)) # 7 days before that from_date = midnight - relativedelta(days=7) # a week after from date to_date = from_date + relativedelta(days=7) return from_date, to_date
def test_time_filter_uses_timezone(self): hour = 5 datetime = timezone.now().replace( tzinfo=pytz.utc, hour=hour, minute=0, second=0, microsecond=0, ) tz = pytz.timezone('Europe/Berlin') offset_hours = int(tz.utcoffset(datetime.utcnow()).seconds / 3600) with timezone.override(tz), translation.override('en'): val = time_filter(datetime) self.assertEqual(val, '{}:00 AM'.format(hour + offset_hours))
def test_get_current_timezone_templatetag_with_pytz(self): """ Test the {% get_current_timezone %} templatetag with pytz. """ tpl = Template( "{% load tz %}{% get_current_timezone as time_zone %}{{ time_zone }}" ) with timezone.override(pytz.timezone('Europe/Paris')): self.assertEqual(tpl.render(Context()), "Europe/Paris") tpl = Template( "{% load tz %}{% timezone 'Europe/Paris' %}{% get_current_timezone as time_zone %}{% endtimezone %}{{ time_zone }}" ) self.assertEqual(tpl.render(Context()), "Europe/Paris")
def test_localdate(self): naive = datetime.datetime(2015, 1, 1, 0, 0, 1) with self.assertRaisesMessage( ValueError, 'localtime() cannot be applied to a naive datetime'): timezone.localdate(naive) with self.assertRaisesMessage( ValueError, 'localtime() cannot be applied to a naive datetime'): timezone.localdate(naive, timezone=EAT) aware = datetime.datetime(2015, 1, 1, 0, 0, 1, tzinfo=ICT) self.assertEqual(timezone.localdate(aware, timezone=EAT), datetime.date(2014, 12, 31)) with timezone.override(EAT): self.assertEqual(timezone.localdate(aware), datetime.date(2014, 12, 31)) with mock.patch('django.utils.timezone.now', return_value=aware): self.assertEqual(timezone.localdate(timezone=EAT), datetime.date(2014, 12, 31)) with timezone.override(EAT): self.assertEqual(timezone.localdate(), datetime.date(2014, 12, 31))
def test_override(self): default = timezone.get_default_timezone() try: timezone.activate(ICT) with timezone.override(EAT): self.assertIs(EAT, timezone.get_current_timezone()) self.assertIs(ICT, timezone.get_current_timezone()) with timezone.override(None): self.assertIs(default, timezone.get_current_timezone()) self.assertIs(ICT, timezone.get_current_timezone()) timezone.deactivate() with timezone.override(EAT): self.assertIs(EAT, timezone.get_current_timezone()) self.assertIs(default, timezone.get_current_timezone()) with timezone.override(None): self.assertIs(default, timezone.get_current_timezone()) self.assertIs(default, timezone.get_current_timezone()) finally: timezone.deactivate()
def test_rules_time_isafter_custom_time(event, position, clist): # Ticket is valid starting at a custom time event.settings.timezone = 'Europe/Berlin' clist.rules = {"isAfter": [{"var": "now"}, {"buildTime": ["customtime", "22:00:00"]}, None]} clist.save() with freeze_time("2020-01-01 21:55:00+01:00"), override(event.timezone): assert not OrderPosition.objects.filter(SQLLogic(clist).apply(clist.rules), pk=position.pk).exists() with pytest.raises(CheckInError) as excinfo: perform_checkin(position, clist, {}) assert excinfo.value.code == 'rules' assert 'Only allowed after 22:00' in str(excinfo.value) with freeze_time("2020-01-01 22:05:00+01:00"): assert OrderPosition.objects.filter(SQLLogic(clist).apply(clist.rules), pk=position.pk).exists() perform_checkin(position, clist, {})
def test_extract_func_explicit_timezone_priority(self): start_datetime = microsecond_support(datetime(2015, 6, 15, 23, 30, 1, 321)) end_datetime = microsecond_support(datetime(2015, 6, 16, 13, 11, 27, 123)) start_datetime = timezone.make_aware(start_datetime, is_dst=False) end_datetime = timezone.make_aware(end_datetime, is_dst=False) self.create_model(start_datetime, end_datetime) melb = pytz.timezone('Australia/Melbourne') with timezone.override(melb): model = DTModel.objects.annotate( day_melb=Extract('start_datetime', 'day'), day_utc=Extract('start_datetime', 'day', tzinfo=timezone.utc), ).order_by('start_datetime').get() self.assertEqual(model.day_melb, 16) self.assertEqual(model.day_utc, 15)
def testExtremeTimeZones(self): lions = RecurringEventPage(owner = self.user, slug = "pago-pago-lions", title = "Pago Pago Lions Club", repeat = Recurrence(dtstart=dt.date(2015,2,1), freq=MONTHLY, byweekday=[TH(1),TH(3)]), time_from = dt.time(23,0), tz = pytz.timezone("Pacific/Pago_Pago"), location = "Lions Den, Tafuna, PagoPago", website = "http://www.lionsclubs.org.nz") self.calendar.add_child(instance=lions) with timezone.override("Pacific/Kiritimati"): self.assertEqual(lions.when, "The Saturday after the first Thursday and " "Saturday after the third Thursday of the month at 12am")
def test_date_filter_uses_timezone(self): # 11pm on Sunday UTC datetime = timezone.now().replace( tzinfo=pytz.utc, year=2018, month=3, day=11, hour=23, minute=0, second=0, microsecond=0, ) with timezone.override(pytz.timezone('Europe/Berlin')): # ... is Monday in Berlin val = date_filter(datetime) self.assertIn('Monday', val)
def get_emp_who_left_on_break(start, stop): """ Filters employees who clocked out before the stop :param start: datetime object the start of time that you want to look at :param stop: datetime object the end of time that you want to look at :return: filtered objects within the start and stop range """ with timezone.override("US/Eastern"): return EmpClockDataModel.objects.filter( CLOCK_IN_TIME__year=start.year, CLOCK_IN_TIME__month=start.month, CLOCK_IN_TIME__day=start.day, CLOCK_OUT_TIME__lte=stop, CLOCK_OUT_REASON__exact='&break', ).exclude(CLOCK_OUT_TIME__lte=start)
def daily_activity_notifications(): with timer() as t: for group in Group.objects.all(): with timezone.override(group.timezone): if timezone.localtime().hour != 20: # only at 8pm local time continue for data in fetch_activity_notification_data_for_group(group): prepare_activity_notification_email(**data).send() stats.activity_notification_email( group=data['group'], **{k: v.count() for k, v in data.items() if isinstance(v, QuerySet)} ) stats_utils.periodic_task('activities__daily_activity_notifications', seconds=t.elapsed_seconds)
def daily_pickup_notifications(): stats_utils.periodic_task('pickups__daily_pickup_notifications') for group in Group.objects.all(): with timezone.override(group.timezone): if timezone.localtime().hour is not 20: # only at 8pm local time continue for data in fetch_pickup_notification_data_for_group(group): prepare_pickup_notification_email(**data).send() stats.pickup_notification_email(group=data['group'], **{ k: v.count() for k, v in data.items() if isinstance(v, QuerySet) })
def load_raw_data(): # process generator file. CSV has headers. # each row is a dict. with timezone.override('US/Eastern'): for row in read_csv_generator(clock_in_out_csv, headers=True): created_row = EmpClockDataModel.objects.create( EMP_ID_TXT=row['EMP_ID_TXT'], EMP_NAME=row['EMP_NAME'], EMP_DEPT_TXT=row['EMP_DEPT_TXT'], CLOCK_IN_REASON=row['CLOCK_IN_REASON'], CLOCK_IN_TIME=process_date(row['PNCHEVNT_DTM_IN']), CLOCK_OUT_REASON=row['CLOCK_OUT_REASON'], CLOCK_OUT_TIME=process_date(row['PNCHEVNT_DTM_OUT']), ) created_row.save() print("LOADED Raw Clock Data Row")
def test_admin_course_run_change_view_post(self): """ Validate that the course run can be updated via the admin. """ user = UserFactory(is_staff=True, is_superuser=True) self.client.login(username=user.username, password="******") # Create a course run course_run = CourseRunFactory() # Get the admin change view url = reverse("admin:courses_courserun_change", args=[course_run.id]) data = { "languages": ["fr", "en"], "resource_link": "https://example.com/my-resource-link", "start_0": "2015-01-15", "start_1": "07:06:15", "end_0": "2015-01-30", "end_1": "23:52:34", "enrollment_start_0": "2015-01-02", "enrollment_start_1": "13:13:07", "enrollment_end_0": "2015-01-23", "enrollment_end_1": "09:07:11", } with timezone.override(pytz.utc): response = self.client.post(url, data) self.assertEqual(response.status_code, 302) # Check that the course run was updated as expected course_run.refresh_from_db() self.assertEqual(course_run.languages, ["fr", "en"]) self.assertEqual( course_run.resource_link, "https://example.com/my-resource-link" ) self.assertEqual( course_run.start, datetime(2015, 1, 15, 7, 6, 15, tzinfo=pytz.utc) ) self.assertEqual( course_run.end, datetime(2015, 1, 30, 23, 52, 34, tzinfo=pytz.utc) ) self.assertEqual( course_run.enrollment_start, datetime(2015, 1, 2, 13, 13, 7, tzinfo=pytz.utc), ) self.assertEqual( course_run.enrollment_end, datetime(2015, 1, 23, 9, 7, 11, tzinfo=pytz.utc) )
def export(event: Event, fileid: str, provider: str, form_data: Dict[str, Any]) -> None: file = CachedFile.objects.get(id=fileid) with language(event.settings.locale), override(event.settings.timezone): responses = register_data_exporters.send(event) for receiver, response in responses: ex = response(event) if ex.identifier == provider: d = ex.render(form_data) if d is None: raise ExportError( ugettext('Your export did not contain any data.')) file.filename, file.type, data = d file.file.save(cachedfile_name(file, file.filename), ContentFile(data)) file.save() return file.pk
def clean(self): if ( self.cleaned_data['date'] is None or self.cleaned_data['time'] is None ): servertz = timezone.get_default_timezone() with timezone.override(self.instance.timezone): usertz = timezone.get_current_timezone() self.instance.date = timezone.make_naive( timezone.localtime( timezone.make_aware(timezone.now(), servertz), usertz), usertz ) else: self.instance.date = datetime.combine( self.cleaned_data['date'], self.cleaned_data['time']) return super(SubmitCaffeineForm, self).clean()
def now(self, request): data = TimezoneForm(request.query_params) if not data.is_valid(): raise DRFValidationError(data.errors) requested_timezone = data.cleaned_data.get('timezone') tz = requested_timezone or pytz.utc now = utils.timezone.now() transmissions = Transmission.at(now) try: transmission = transmissions.next() except StopIteration: return Response(None) else: serializer = self.get_serializer(transmission, many=False) with override(timezone=tz): return Response(serializer.data)
def test_without_change(self, monkeypatch): """ When timezone and language are not provided mixin should use timezone and language that are already active """ berlin = pytz.timezone("Europe/Berlin") def check(): assert translation.get_language() == 'de' assert timezone.get_current_timezone() == berlin with nested(timezone.override(berlin), translation.override('de')): mixin = mixins.LocalizationMixin() monkeypatch.setattr(mixin, 'get_message', check) mixin.build() assert timezone.get_current_timezone() == berlin assert translation.get_language() == 'de'
def send_meeting_change_notification(old_meeting, new_meeting): study_group = new_meeting.study_group to = [ su.email for su in study_group.application_set.active().filter( accepted_at__isnull=False).exclude(email='') ] context = { 'old_meeting': old_meeting, 'new_meeting': new_meeting, 'learning_circle': study_group, } with use_language(study_group.language), timezone.override( pytz.timezone(study_group.timezone)): subject = render_to_string_ctx( 'studygroups/email/meeting_changed-subject.txt', context).strip('\n') html_body = render_to_string_ctx( 'studygroups/email/meeting_changed.html', context) text_body = html_body_to_text(html_body) sms_body = render_to_string_ctx( 'studygroups/email/meeting_changed-sms.txt', context).strip('\n') notification = EmailMultiAlternatives(subject, text_body, settings.DEFAULT_FROM_EMAIL, bcc=to) notification.attach_alternative(html_body, 'text/html') try: notification.send() except Exception as e: logger.exception('Could not send meeting change notification', exc_info=e) applications = study_group.application_set.active().filter( accepted_at__isnull=False).exclude(mobile='') applications = applications.filter(mobile_opt_out_at__isnull=True) tos = [su.mobile for su in applications] for to in tos: try: send_message(to, sms_body) except TwilioRestException as e: logger.exception("Could not send text message to %s", to, exc_info=e)
def handle(self, *args, **options): try: o = Organizer.objects.get(slug=options['organizer_slug'][0]) except Organizer.DoesNotExist: self.stderr.write(self.style.ERROR('Organizer not found.')) sys.exit(1) with scope(organizer=o): try: e = o.events.get(slug=options['event_slug'][0]) except Event.DoesNotExist: self.stderr.write(self.style.ERROR('Event not found.')) sys.exit(1) pbar = tqdm(total=100) def report_status(val): pbar.update(round(val, 2) - pbar.n) with language(e.settings.locale), override(e.settings.timezone): responses = register_data_exporters.send(e) for receiver, response in responses: ex = response(e, report_status) if ex.identifier == options['export_provider'][0]: params = json.loads(options.get('parameters') or '{}') with open(options['output_file'][0], 'wb') as f: try: ex.render(form_data=params, output_file=f) except TypeError: self.stderr.write( self.style.WARNING( 'Provider does not support direct file writing, need to buffer export in memory.' )) d = ex.render(form_data=params) if d is None: self.stderr.write( self.style.ERROR('Empty export.')) sys.exit(2) f.write(d[2]) sys.exit(0) pbar.close() self.stderr.write(self.style.ERROR('Export provider not found.')) sys.exit(1)
def cron_preview(request): schedule = request.POST.get("schedule") tz = request.POST.get("tz") ctx = {"tz": tz, "dates": []} try: with timezone.override(tz): now_naive = timezone.make_naive(timezone.now()) it = croniter(schedule, now_naive) for i in range(0, 6): naive = it.get_next(datetime) aware = timezone.make_aware(naive) ctx["dates"].append((naive, aware)) except UnknownTimeZoneError: ctx["bad_tz"] = True except: ctx["bad_schedule"] = True return render(request, "front/cron_preview.html", ctx)
def send_notification(logentry_id: int, action_type: str, user_id: int, method: str): logentry = LogEntry.all.get(id=logentry_id) if logentry.event: sm = lambda: scope(organizer=logentry.event.organizer) # noqa else: sm = lambda: scopes_disabled() # noqa with sm(): user = User.objects.get(id=user_id) types = get_all_notification_types(logentry.event) notification_type = types.get(action_type) if not notification_type: return # Ignore, e.g. plugin not active for this event with language(user.locale), override(logentry.event.timezone if logentry.event else user.timezone): notification = notification_type.build_notification(logentry) if method == "mail": send_notification_mail(notification, user)
def render(self, request, templates, context, tz=None, **kwargs): logger.debug( "{app}.render: {request.path}".format( app=self.__class__.__name__, request=request ) ) context.update({"application": self}) kwargs.setdefault("context", context) response = TemplateResponse(request, templates, **kwargs) response.current_app = self.current_app if tz is not None: with timezone.override(tz): response.render() if not request.user.is_anonymous: patch_cache_control(response, private=True) return response
def refresh(self, request, pk=None): try: with transaction.atomic(): task = Task.objects.select_for_update(skip_locked=True).get( pk=pk) if task.owner != request.user: raise PermissionDenied() with timezone.override(None): task.update() task.last_update = timezone.now() task.save() serializer = TaskSerializer(task, context={'request': request}) return Response(serializer.data, status=status.HTTP_201_CREATED) except (ClientError, TimeoutError) as e: logger.error('[Proxy Down]', exc_info=e) raise ServiceUnavailable() except BaseException as e: logger.fatal('[Unknow Error]', exc_info=e) raise APIException()