def calendar(request): if request.user.is_superuser: return redirect('/dashboard') try: patient = Patient.objects.get(user=request.user) except Patient.DoesNotExist: patient = None try: doctor = Doctor.objects.get(user=request.user) except Doctor.DoesNotExist: doctor = None if patient != None: #They're a patient. type = 'patient' appointments = Appointment.objects.filter(dr=patient.doctor) elif doctor != None: type = 'doctor' appointments = Appointment.objects.filter(dr=doctor) else: appointments = None appointmentlist = [] for appointment in appointments: # start = appointment.when - datetime.timedelta(hours=4) start = localtime(appointment.when) # end = appointment.endtime - datetime.timedelta(hours=4) end = localtime(appointment.endtime) #newstart = appointment.when - datetime.timedelta(hours=4) #newend = appointment.endtime - datetime.timedelta(hours=4) title = str(start.strftime('%H:%M')) + " - " + str( end.strftime('%H:%M') ) + " " + appointment.ptient.first_name + " " + appointment.ptient.last_name appointmentlist.append({'title': title, 'start': start, 'end': end}) ''' calendar_config_options = {'header': { 'left': 'prev,next today', 'center': 'title', 'right': 'month,agendaWeek,agendaDay' }, 'defaultView': 'agendaWeek', 'editable': 'True', # View only. 'events': json.dumps(appointmentlist), 'firstDay': 1 # Week starts on Monday. }''' event_url = 'calendarEvents/' #return HttpResponse(events_to_json(appointments), content_type='application/json') return render( request, 'calendar.html', { 'appointmentlist': json.dumps(appointmentlist, default=date_handler), 'type': type, 'patient': patient })
def sortidaiCal(request): cal = Calendar() cal.add('method', 'PUBLISH') # IE/Outlook needs this for instance in Sortida.objects.filter( calendari_desde__isnull=False).exclude(estat__in=[ 'E', 'P', ]).all(): event = Event() # d=instance.data_inici # t=instance.franja_inici.hora_inici # dtstart = datetime( d.year, d.month, d.day, t.hour, t.minute ) # d=instance.data_fi # t=instance.franja_fi.hora_fi # dtend = datetime( d.year, d.month, d.day, t.hour, t.minute ) summary = u"{ambit}: {titol}".format( ambit=instance.ambit, titol=instance.titol_de_la_sortida) event.add('dtstart', localtime(instance.calendari_desde)) event.add('dtend', localtime(instance.calendari_finsa)) event.add('summary', summary) organitzador = u"\nOrganitza: " organitzador += u"{0}".format( u"Departament" + instance.departament_que_organitza.nom if instance. departament_que_organitza_id else u"") organitzador += " " + instance.comentari_organitza event.add( 'organizer', vText(u"{0} {1}".format( u"Departament " + instance.departament_que_organitza.nom if instance.departament_que_organitza_id else u"", instance.comentari_organitza))) event.add('description', instance.programa_de_la_sortida + organitzador) event.add('uid', 'djau-ical-{0}'.format(instance.id)) event['location'] = vText(instance.ciutat) cal.add_component(event) # response = HttpResponse( cal.to_ical() , content_type='text/calendar') # response['Filename'] = 'shifts.ics' # IE needs this # response['Content-Disposition'] = 'attachment; filename=shifts.ics' # return response return HttpResponse(cal.to_ical())
def convert_time(time, to_func=None): if not to_func: return time if callable(to_func): return to_func(time) if to_func == "localtime": return tz.localtime(time) return tz.utc(time)
def str_date(value): try: return_value = localtime(parse(value)) return (return_value.strftime("%-I:%M") + return_value.strftime("%p").lower() + " " + return_value.strftime("%d %B " "%Y")) except ValueError: return
def get_date(time=None, locale=True, days=0, default=timezone.now): if isinstance(time, date) and not isinstance(time, datetime): return time + days * DURATION_DAY time = time or default() if locale: time = tz.localtime(time) else: time = tz.utc(time) time = time + days * DURATION_DAY return time.date()
def format_short_time(time=None, length=10, padding="0123456789"): time = tz.localtime(time or timezone.now()) s = "{:02d}{:03d}{:05d}".format( time.year % 100, (time.month - 1) * 32 + time.day + int(time.year // 100 == 19) * 512, (time.hour * 64 * 64) + (time.minute * 64) + time.second, ) if length and length > len(s): s += "".join([random.choice(padding) for i in range(length - len(s))]) return s
def get_day_range(time=None, to_utc=True, default=datetime.now, cross=True, **kwargs): if not time: time = default() if isinstance(time, date) and not isinstance(time, datetime): time = datetime.strptime(time.strftime("%Y-%m-%d"), "%Y-%m-%d") if kwargs: time += timedelta(**kwargs) time = tz.localtime(time) time = time.replace(hour=0, minute=0, second=0, microsecond=0) delta = DURATION_MICROSECOND * (0 if cross else 1) return convert_time(time, to_utc), convert_time(time + DURATION_DAY - delta, to_utc)
def sortidaiCal( request): cal = Calendar() cal.add('method','PUBLISH' ) # IE/Outlook needs this for instance in Sortida.objects.filter( calendari_desde__isnull = False ).exclude(estat__in = ['E', 'P', ]).all(): event = Event() # d=instance.data_inici # t=instance.franja_inici.hora_inici # dtstart = datetime( d.year, d.month, d.day, t.hour, t.minute ) # d=instance.data_fi # t=instance.franja_fi.hora_fi # dtend = datetime( d.year, d.month, d.day, t.hour, t.minute ) summary = u"{ambit}: {titol}".format(ambit=instance.ambit , titol= instance.titol_de_la_sortida) event.add('dtstart',localtime(instance.calendari_desde) ) event.add('dtend' ,localtime(instance.calendari_finsa) ) event.add('summary',summary) organitzador = u"\nOrganitza: " organitzador += u"{0}".format( u"Departament" + instance.departament_que_organitza.nom if instance.departament_que_organitza_id else u"" ) organitzador += " " + instance.comentari_organitza event.add('organizer', vText( u"{0} {1}".format( u"Departament " + instance.departament_que_organitza.nom if instance.departament_que_organitza_id else u"" , instance.comentari_organitza ))) event.add('description',instance.programa_de_la_sortida + organitzador) event.add('uid', 'djau-ical-{0}'.format( instance.id ) ) event['location'] = vText( instance.ciutat ) cal.add_component(event) # response = HttpResponse( cal.to_ical() , content_type='text/calendar') # response['Filename'] = 'shifts.ics' # IE needs this # response['Content-Disposition'] = 'attachment; filename=shifts.ics' # return response return HttpResponse( cal.to_ical() )
def test_shows_problem_details(self): problem = create_test_problem({'organisation': self.organisation}) problem.status = Problem.RESOLVED problem.save() resp = self.client.get(self.live_feed_url) self.assertEqual(resp.status_code, 200) problem_url = reverse('problem-view', kwargs={'pk': problem.id, 'cobrand': 'choices'}) self.assertContains(resp, problem_url) self.assertContains(resp, problem.organisation.name) self.assertContains(resp, django_date(localtime(problem.created), formats.DATETIME_FORMAT)) self.assertContains(resp, problem.get_category_display()) self.assertContains(resp, problem.get_status_display())
def fmt_datetime(d, fmt='', local=True): """ format date with local support ``d``: datetime to format ``fmt``: format, default is '%Y-%m-%d %H-%M' ``local``: format as local time """ if not d: return '' if local: from django.templatetags.tz import localtime d = localtime(d) if not fmt: fmt = '%Y-%m-%d %H-%M' return d.strftime(fmt)
def timetag_filter(value, arg=None): """Formats a date as a time since if less than 1 day old or as a date otherwise Will return <time...> html tag as part of the output. """ if not value: return value = _dt(value) arg = _dt(arg) if arg - value > timedelta(days=1): label = date(value, 'Y-m-d') else: label = timesince(value, arg) + " ago" return mark_safe("<time datetime=\"%s\" title=\"%s\">%s</time>" % (date(value, 'Y-m-d\TH:i:sO'), date(localtime(value), 'Y-m-d H:i:sO'), label))
def test_shows_review_details(self): review = create_test_review({'organisation': self.organisation}) resp = self.client.get(self.live_feed_url) self.assertEqual(resp.status_code, 200) review_url = reverse( 'review-detail', kwargs={ 'api_posting_id': review.api_posting_id, 'ods_code': review.organisations.all()[0].ods_code, 'cobrand': 'choices' } ) self.assertContains(resp, review_url) self.assertContains(resp, review.organisations.all()[0].name) self.assertContains(resp, django_date(localtime(review.api_published), formats.DATETIME_FORMAT)) self.assertContains(resp, capfirst(review.title))
def next_update(self, obj): return localize(localtime(obj.next_update))
def wrapper(datetime, *args, **kwargs): if getattr(datetime, 'convert_to_local_time', True): datetime = localtime(datetime) return func(datetime, *args, **kwargs)
def comparteixCalendari(request, clau): cal = Calendar() cal.add('method', 'PUBLISH') # IE/Outlook needs this try: dades_adicionals_professor = DadesAddicionalsProfessor.objects.get( clauDeCalendari=clau) professor = dades_adicionals_professor.professor except: return HttpResponseNotFound("") else: #-- imparticions imparticions = list( Impartir.objects.filter(horari__professor=professor). select_related("reserva").select_related( "reserva__aula").select_related("horari").select_related( "horari__hora").select_related("horari__assignatura")) for instance in imparticions: event = Event() assignatura = instance.horari.assignatura.nom_assignatura aula = instance.reserva.aula.nom_aula if hasattr( instance, "reserva") and instance.reserva is not None else "" grup = instance.horari.grup.descripcio_grup if hasattr( instance.horari, "grup") and instance.horari.grup is not None else "" summary = u"{assignatura} {aula} {grup}".format( assignatura=assignatura, aula=aula, grup=grup, ) d = instance.dia_impartir h = instance.horari.hora event.add( 'dtstart', localtime( datetime(d.year, d.month, d.day, h.hora_inici.hour, h.hora_inici.minute, h.hora_inici.second))) event.add( 'dtend', localtime( datetime(d.year, d.month, d.day, h.hora_fi.hour, h.hora_fi.minute, h.hora_fi.second))) event.add('summary', summary) event.add('uid', 'djau-ical-impartir-{0}'.format(instance.id)) event['location'] = vText(aula) cal.add_component(event) #-- sortides q_professor = Q(professor_que_proposa=professor) q_professor |= Q(altres_professors_acompanyants=professor) q_professor |= Q(professors_responsables=professor) sortides = list( Sortida.objects.filter(q_professor).filter( calendari_desde__isnull=False).exclude(estat__in=[ 'E', 'P', ]).distinct()) for instance in sortides: event = Event() summary = u"{ambit}: {titol}".format( ambit=instance.ambit, titol=instance.titol_de_la_sortida) event.add('dtstart', localtime(instance.calendari_desde)) event.add('dtend', localtime(instance.calendari_finsa)) event.add('summary', summary) organitzador = u"\nOrganitza: " organitzador += u"{0}".format( u"Departament" + instance.departament_que_organitza.nom if instance. departament_que_organitza_id else u"") organitzador += " " + instance.comentari_organitza event.add( 'organizer', vText(u"{0} {1}".format( u"Departament " + instance.departament_que_organitza.nom if instance.departament_que_organitza_id else u"", instance.comentari_organitza))) event.add('description', instance.programa_de_la_sortida + organitzador) event.add('uid', 'djau-ical-sortida-{0}'.format(instance.id)) event['location'] = vText(instance.ciutat) cal.add_component(event) return HttpResponse(cal.to_ical())
def item_date(self, item): return localtime(item['date'])
async def receive_json(self, content): if self.user.is_authenticated: json_type = content.get('type', None) if json_type == 'leave_room': await self.remove_user_from_room(self.user.pk) dict_message = { 'USER_LEFT': { 'username': str(self.user), 'room': self.room.name, "timestamp": date(localtime(now()), settings.DATETIME_FORMAT) } } await ChatMessageHelper.send_message(self.room, json.dumps(dict_message)) elif json_type == 'user_typing': for group_name in self.groups: await self.channel_layer.group_send( group_name, { 'type': 'user_typing', 'username': str(self.user), 'text': ChatMessageHelper.message_from_type( 'USER_TYPING', username=str(self.user)) }) elif json_type == 'room_members': await self.send_room_members() elif json_type == 'remove_member': user_ids = content.get('user_id', None) user = await self.get_user(user_ids) await self.remove_user_from_room(user_ids) dict_message = { 'USER_LEFT': { 'username': str(user), 'room': self.room.name, "timestamp": date(localtime(now()), settings.DATETIME_FORMAT) } } await ChatMessageHelper.send_message(self.room, json.dumps(dict_message)) elif json_type == 'add_members': user_ids = content.get('user_ids', None) if user_ids is not None: user_ids = list(map(int, user_ids)) if self.room.is_user_to_user_room: new_room = await self.get_or_create_group_room(user_ids ) for group_name in self.groups: await self.channel_layer.group_send( group_name, { 'type': 'new_room', 'slug': new_room.slug, }) else: users = await self.add_room_users(user_ids) for user in users: dict_message = { 'USER_JOINED': { 'username': str(user.user) } } await ChatMessageHelper.send_message( self.room, json.dumps(dict_message)) await self.send_room_members() else: text = content['message'] # update last read flag of current room user (create if not exists) await self.update_room_user(self.room, self.user) message = Message.objects.create(room=self.room, user=self.user, text=text) # update modified timestamp self.room.save() # Send message to room group for group_name in self.groups: await self.channel_layer.group_send( group_name, { 'type': 'chat_message', 'message': url_anchor(text), 'username': str(self.user), 'timestamp': date(localtime(message.created), settings.DATETIME_FORMAT) }) for group_name in self.room.user_groups: await self.channel_layer.group_send( group_name, { 'type': 'chat_message', })
def report_at(self, obj): return tz.localtime(obj.parent_msg.sent_at).strftime("%Y-%m-%d %H:%M")
def _get_timestamp_seconds(self): "Return the time as the number of seconds since midnight" return seconds_since_midnight(localtime(self.timestamp))
def TraeActualizado(self, objeto): return "%s" % (localtime( objeto.actualizado).strftime("%d-%m-%y %I:%M %p"))
def viewer_date(email_or_thread): if hasattr(email_or_thread, "date"): date_obj = email_or_thread.date elif hasattr(email_or_thread, "date_active"): date_obj = email_or_thread.date_active return localtime(date_obj.replace(tzinfo=tzutc()))
async def websocket_connect(self, message): room_slug = self.scope['url_route']['kwargs']['room_slug'] # init variables self.user = self.scope['user'] self.room = await self.get_room(room_slug) self.groups.append(self.room.group_name) type = message['type'] await super().websocket_connect(message) if await self.get_room_user() is None: # create new room if user is added to user_to_user room if self.room.is_user_to_user_room: new_room = await self.get_or_create_group_room([self.user.id]) for group_name in self.groups: await self.channel_layer.group_send( group_name, { 'type': 'new_room', 'slug': new_room.slug, }) return else: await ChatMessageHelper.send_message( self.room, json.dumps({'USER_JOINED': { 'username': str(self.user) }})) # update last read flag of current room user await self.update_room_user(self.room, self.user) # send room properties self.user_count = await ChatMessageHelper.get_user_count(self.room) await self.send_json( content={ 'type': 'room_properties', 'room_name': self.room.name, 'room_id': self.room.pk, 'room_slug': room_slug, 'room_modified': date(localtime(self.room.modified), settings.DATETIME_FORMAT), 'user_count': self.user_count, 'is_user_to_user': self.room.is_user_to_user_room }) # init room with previous messages for message in await self.get_room_messages(): await self.send_json( content={ 'type': type, 'message': url_anchor(str(message)), 'timestamp': date(localtime(message.created), settings.DATETIME_FORMAT), 'username': str(message.user) if message.user is not None else None, }) await self.channel_layer.group_send( f'unread-chat-messages-{self.user.pk}', { 'type': 'chat_message', })
def viewer_date(email_or_thread): if hasattr(email_or_thread, 'date'): date_obj = email_or_thread.date elif hasattr(email_or_thread, 'date_active'): date_obj = email_or_thread.date_active return localtime(date_obj.replace(tzinfo=tzutc()))
def str_date_only(value): return localtime(parse(value)).strftime("%d %B %Y")
def repr_time(time, format="%Y-%m-%d %H:%M", falsy=""): return tz.localtime(time).strftime(format) if time else falsy