def test_create_no_holidays(self): """test create appointment, no holiday to avoid after 1900""" import_holidays() appt_datetime = Arrow.fromdatetime(datetime(1900, 1, 1)).datetime expected_appt_datetime = Arrow.fromdatetime(datetime(1900, 1, 2)).datetime creator = AppointmentCreator( subject_identifier=self.subject_identifier, visit_schedule_name=self.visit_schedule.name, schedule_name=self.schedule.name, visit=self.visit1000, timepoint_datetime=appt_datetime, ) self.assertEqual(Appointment.objects.all()[0], creator.appointment) self.assertEqual(Appointment.objects.all()[0].appt_datetime, expected_appt_datetime) appt_datetime = Arrow.fromdatetime(datetime(2017, 1, 1)).datetime creator = AppointmentCreator( subject_identifier=self.subject_identifier, visit_schedule_name=self.visit_schedule.name, schedule_name=self.schedule.name, visit=self.visit1000, timepoint_datetime=appt_datetime, ) self.assertEqual(Appointment.objects.all()[0], creator.appointment) self.assertEqual(Appointment.objects.all()[0].appt_datetime, appt_datetime)
def year_range(date): start_date = datetime.datetime(date.year, 1, 1) end_date = datetime.datetime(date.year, 12, 31) start_date = Arrow.fromdatetime(start_date) end_date = Arrow.fromdatetime(end_date) return (start_date, end_date)
def test_available_arw_with_holiday(self): """Asserts finds available_arw on first clinic day after holiday.""" suggested_date = Arrow.fromdatetime(datetime(2017, 1, 1)).datetime expected_date = Arrow.fromdatetime(datetime(2017, 1, 8)).datetime facility = Facility(name="clinic", days=[suggested_date.weekday()], slots=[100]) available_arw = facility.available_arw(suggested_date) self.assertEqual(expected_date, available_arw.datetime)
def month_range(date): # https://stackoverflow.com/questions/42950/get-last-day-of-the-month-in-python/27667421#27667421 start_date = datetime.datetime(date.year, date.month, 1) end_date = start_date + relativedelta(months=1, days=-1) start_date = Arrow.fromdatetime(start_date) end_date = Arrow.fromdatetime(end_date) return (start_date, end_date)
def test_read_holidays_from_db(self): """Asserts finds available_arw on first clinic day after holiday.""" suggested_date = Arrow.fromdatetime(datetime(2017, 1, 1)).datetime expected_date = Arrow.fromdatetime(datetime(2017, 1, 8)).datetime Holiday.objects.create(local_date=suggested_date) facility = Facility(name="clinic", days=[suggested_date.weekday()], slots=[100]) available_arw = facility.available_arw(suggested_date) self.assertEqual(expected_date, available_arw.datetime)
def test_create(self): appt_datetime = Arrow.fromdatetime(datetime(2017, 1, 1)).datetime creator = AppointmentCreator( subject_identifier=self.subject_identifier, visit_schedule_name=self.visit_schedule.name, schedule_name=self.schedule.name, visit=self.visit1000, timepoint_datetime=appt_datetime) appointment = creator.appointment self.assertEqual( Appointment.objects.all()[0], appointment) self.assertEqual( Appointment.objects.all()[0].appt_datetime, Arrow.fromdatetime(datetime(2017, 1, 3)).datetime)
def setUp(self): self.subject_identifier = "111111111" self.reference_helper = self.reference_helper_cls( visit_model=self.visit_model, subject_identifier=self.subject_identifier) report_datetime = Arrow.fromdatetime(datetime(2017, 7, 7)).datetime self.reference_helper.create_visit( report_datetime=report_datetime, visit_schedule_name="visit_schedule", schedule_name="schedule", visit_code=DAY1, timepoint=Decimal("1.0"), ) self.reference_helper.create_visit( report_datetime=report_datetime + relativedelta(days=3), visit_schedule_name="visit_schedule", schedule_name="schedule", visit_code=DAY3, timepoint=Decimal("1.0"), ) self.reference_helper.create_visit( report_datetime=report_datetime + relativedelta(days=5), visit_schedule_name="visit_schedule", schedule_name="schedule", visit_code=DAY5, timepoint=Decimal("1.0"), )
def load_time_jp(self, timestamp) -> Arrow: tz = datetime.timezone(datetime.timedelta(hours=8)) d_time = datetime.datetime.fromtimestamp(timestamp, tz) a_time = Arrow.fromdatetime(d_time) if a_time.hour < 4: a_time -= datetime.timedelta(hours=4) return a_time
def label_context(self): tz = pytz.timezone(settings.TIME_ZONE) local = Arrow.fromdatetime(self.requisition.drawn_datetime or self.requisition.created).to(tz) formatted_date = local.format("YYYY-MM-DD HH:mm") printed = "PRINTED: " if not self.requisition.drawn_datetime else "DRAWN: " drawn_datetime = f"{printed}{formatted_date}" try: clinician_initials = self.requisition.user_created[0:2].upper() except IndexError: clinician_initials = "??" return { "requisition_identifier": self.requisition.requisition_identifier, "item": self.item, "item_count": self.requisition.item_count or 1, "primary": "<P>", "barcode_value": self.requisition.requisition_identifier, "protocol": Protocol().protocol, "site": str(self.requisition.site.id), "site_name": str(self.requisition.site.name), "site_title": str(self.requisition.site.siteprofile.title), "clinician_initials": clinician_initials, "drawn_datetime": drawn_datetime, "subject_identifier": self.registered_subject.subject_identifier, "gender": self.registered_subject.gender, "dob": self.registered_subject.dob, "initials": self.registered_subject.initials, "identity": self.registered_subject.identity, "alpha_code": self.requisition.panel_object.alpha_code, "panel": self.requisition.panel_object.abbreviation, "panel_name": self.requisition.panel.display_name, }
def test_create(self): """test create appointment, avoids new years holidays""" appt_datetime = Arrow.fromdatetime(datetime(2017, 1, 1)).datetime creator = AppointmentCreator( subject_identifier=self.subject_identifier, visit_schedule_name=self.visit_schedule.name, schedule_name=self.schedule.name, visit=self.visit1000, timepoint_datetime=appt_datetime, ) appointment = creator.appointment self.assertEqual(Appointment.objects.all()[0], appointment) self.assertEqual( Appointment.objects.all()[0].appt_datetime, Arrow.fromdatetime(datetime(2017, 1, 3)).datetime, )
def test_create_appt_moves_forward(self): """Assert appt datetime moves forward to avoid holidays""" appt_datetime = Arrow.fromdatetime(datetime(2017, 1, 1)).datetime creator = AppointmentCreator( subject_identifier=self.subject_identifier, visit_schedule_name=self.visit_schedule.name, schedule_name=self.schedule.name, visit=self.visit1000, timepoint_datetime=appt_datetime, ) appointment = creator.appointment self.assertEqual(Appointment.objects.all()[0], appointment) self.assertEqual( Appointment.objects.all()[0].appt_datetime, Arrow.fromdatetime(datetime(2017, 1, 3)).datetime, )
def __init__(self, **kwargs): super().__init__(**kwargs) self.longitudinal_refset.order_by('hiv_result_datetime') elisa_hiv_result = None elisa_hiv_result_datetime = None # try to get the first POS for index, result in enumerate( self.longitudinal_refset.fieldset('hiv_result')): if result == POS: elisa_hiv_result = result elisa_hiv_result_datetime = self.longitudinal_refset.fieldset( 'hiv_result_datetime')[index] break # if not, get the most recent result (last) if not elisa_hiv_result: elisa_hiv_result = self.longitudinal_refset.fieldset( 'hiv_result').last() elisa_hiv_result_datetime = self.longitudinal_refset.fieldset( 'hiv_result_datetime').last() self.values.update(elisa_hiv_result=elisa_hiv_result) if elisa_hiv_result_datetime: self.values.update(elisa_hiv_result_date=Arrow.fromdatetime( elisa_hiv_result_datetime).date()) else: self.values.update(elisa_hiv_result_date=None) self.values.update(hiv_result=elisa_hiv_result) self.values.update(hiv_result_datetime=elisa_hiv_result_datetime) self.values.update(elisa_hiv_result=elisa_hiv_result) self.values.update(elisa_hiv_result_datetime=elisa_hiv_result_datetime)
def _data(self): return { '_created': get_utcnow(), 'best_prev_result_date': self.best_prev_result_date, 'documented_pos': self.documented_pos, 'documented_pos_date': self.documented_pos_date, 'final_arv_status': self.final_arv_status, 'final_arv_status_baseline': self.final_arv_status_baseline, 'final_hiv_status': self.final_hiv_status, 'final_hiv_status_date': self.final_hiv_status_date, 'has_tested': self.has_tested, 'indeterminate': self.indeterminate, 'known_positive': self.known_positive, 'naive_at_baseline': self.naive_at_baseline, 'newly_diagnosed': self.newly_diagnosed, 'prev_result': self.prev_result, 'prev_result_date': self.prev_result_date, 'prev_result_known': self.prev_result_known, 'prev_results_discordant': self.prev_results_discordant, 'subject_identifier': self.subject_identifier, 'source_object_name': self.source_object_name, 'today_hiv_result': self.current.today_hiv_result, 'baseline_hiv_result': self.baseline.today_hiv_result, 'current_hiv_result': self.current.today_hiv_result, 'self_reported_result': self.current.self_reported_result, 'current_arv_evidence': self.current.arv_evidence, 'declined': self.declined, 'defaulter_at_baseline': self.defaulter_at_baseline, 'visit_code': self.subject_visit.visit_code, 'visit_date': Arrow.fromdatetime(self.subject_visit.report_datetime).date(), }
def validate_not_future_appt_datetime(self): appt_datetime = self.cleaned_data.get("appt_datetime") if appt_datetime and appt_datetime != NEW_APPT: rappt_datetime = Arrow.fromdatetime(appt_datetime, appt_datetime.tzinfo) if rappt_datetime.to("UTC").date() > get_utcnow().date(): raise forms.ValidationError( {"appt_datetime": "Cannot be a future date."})
def validate_not_future_appt_datetime(self): appt_datetime = self.cleaned_data.get('appt_datetime') if appt_datetime and appt_datetime != NEW_APPT: rappt_datetime = Arrow.fromdatetime( appt_datetime, appt_datetime.tzinfo) if rappt_datetime.to('UTC').date() > get_utcnow().date(): raise forms.ValidationError({ 'appt_datetime': 'Cannot be a future date.'})
def datetime_parser(json_dict): date_format = '%Y-%m-%dT%H:%M:%S.%fZ' date_format2 = '%Y-%m-%d' for (key, value) in json_dict.items(): if value: try: dt = datetime.strptime(value, date_format) json_dict[key] = Arrow.fromdatetime(dt).datetime except TypeError: pass except ValueError: try: dt = datetime.strptime(value[:10], date_format2) json_dict[key] = Arrow.fromdatetime(dt).date() except ValueError: pass return json_dict
def scheduled_appt_datetime(self): scheduled_appt_datetime = None if self.scheduled_appt_date: dt = self.scheduled_appt_date scheduled_appt_datetime = Arrow.fromdatetime( datetime(dt.year, dt.month, dt.day, self.default_time.hour, self.default_time.minute)).datetime return scheduled_appt_datetime
def load_time_cn(self, timestamp) -> Arrow: d_time = datetime.datetime.strptime(timestamp, r"%Y/%m/%d %H:%M") #mahomaho #d_time = datetime.datetime.fromtimestamp(timestamp) #bigfun a_time = Arrow.fromdatetime(d_time) if a_time.time() < datetime.time(hour=5): a_time -= datetime.timedelta(hours=5) return a_time
def test_create_appt_with_lower_greater_than_zero2(self): appt_datetime = Arrow.fromdatetime(datetime(2017, 1, 10)).datetime creator = AppointmentCreator( subject_identifier=self.subject_identifier, visit_schedule_name=self.visit_schedule.name, schedule_name=self.schedule.name, visit=self.visit1010, timepoint_datetime=appt_datetime, ) appointment = Appointment.objects.get(visit_code=self.visit1010.code) self.assertEqual( Appointment.objects.get(visit_code=self.visit1010.code), creator.appointment, ) self.assertEqual( appointment.appt_datetime, Arrow.fromdatetime(datetime(2017, 1, 10)).datetime, )
def validate_assay_datetime(self, assay_datetime, requisition, field): if assay_datetime: assay_datetime = Arrow.fromdatetime( assay_datetime, assay_datetime.tzinfo).to('utc').datetime if assay_datetime < requisition.requisition_datetime: formatted = timezone.localtime(requisition.requisition_datetime).strftime( convert_php_dateformat(settings.SHORT_DATETIME_FORMAT)) raise forms.ValidationError({ field: (f'Invalid. Cannot be before date of ' f'requisition {formatted}.')})
def validate_requisition_datetime(self): requisition_datetime = self.cleaned_data.get('requisition_datetime') subject_visit = self.cleaned_data.get('subject_visit') if requisition_datetime: requisition_datetime = Arrow.fromdatetime( requisition_datetime, requisition_datetime.tzinfo).to('utc').datetime if requisition_datetime < subject_visit.report_datetime: formatted = timezone.localtime(subject_visit.report_datetime).strftime( convert_php_dateformat(settings.SHORT_DATETIME_FORMAT)) raise forms.ValidationError({ 'requisition_datetime': f'Invalid. Cannot be before date of visit {formatted}.'})
def validate_requisition_datetime(self): requisition_datetime = self.cleaned_data.get('requisition_datetime') maternal_visit = self.cleaned_data.get('maternal_visit') if requisition_datetime: requisition_datetime = Arrow.fromdatetime( requisition_datetime, requisition_datetime.tzinfo).to('utc').datetime if requisition_datetime < maternal_visit.report_datetime: formatted = timezone.localtime(maternal_visit.report_datetime).strftime( convert_php_dateformat(settings.SHORT_DATETIME_FORMAT)) raise forms.ValidationError({ 'requisition_datetime': f'Invalid. Cannot be before date of visit {formatted}.'})
def test_create_no_holidays(self): for i in range(1, 7): appt_datetime = Arrow.fromdatetime(datetime(2017, 1, i)).datetime creator = AppointmentCreator( subject_identifier=self.subject_identifier, visit_schedule_name=self.visit_schedule.name, schedule_name=self.schedule.name, visit=self.visit1000, timepoint_datetime=appt_datetime) self.assertEqual( Appointment.objects.all()[0], creator.appointment) self.assertEqual( Appointment.objects.all()[0].appt_datetime, appt_datetime)
def arrow(self, date=None, tz=None): if date is None: return self.utcnow() if tz is None else self.now(tz) else: if tz is None: try: tz = parser.TzinfoParser.parse(date) return self.now(tz) except: pass if isinstance(date, (float, int)): return Arrow.utcfromtimestamp(date) return Arrow.fromdatetime(date) else: tz = parser.TzinfoParser.parse(tz) return Arrow.fromdatetime(date, tz)
def update_status_history(self): try: model_cls = django_apps.get_model(self.status_history_model) except LookupError: pass else: opts = dict(subject_identifier=self.subject_identifier, status_date=Arrow.fromdatetime( self.subject_visit.report_datetime).date(), timepoint=self.subject_visit.visit_code, final_hiv_status=self.final_hiv_status, final_hiv_status_date=self.final_hiv_status_date, final_arv_status=self.final_arv_status) # always create a new instance for this timepoint model_cls.objects.filter(**opts).delete() self.history_obj = model_cls.objects.create(data=self.to_json(), **opts)
def __init__(self, datasource, criteria, kind): self.datasource = datasource self.criteria = criteria self.kind = kind self.maxcount = 50 self.hits = -1 self.querycount = 0 self.machine = Machine(model=self, states=QueryDateRangeNarrower.states, initial='asleep') self.machine.add_transition('start', '*', 'init', after='work') self.machine.add_transition('check', '*', 'finished', conditions=['is_ready']) self.machine.add_transition('step', 'init', 'finished', conditions='is_century_out_of_bounds') self.machine.add_transition('step', 'init', 'whole', after=['runquery', 'check']) self.machine.add_transition('step', 'whole', 'init', conditions='no_hits', after='range_next_century') if self.kind == self.OLDEST: self.date_from = Arrow.fromdatetime(datetime.datetime(1800, 01, 01)) self.date_to = Arrow.fromdatetime(datetime.datetime(1899, 12, 31)) self.factor = +1 self.machine.add_transition('step', 'whole', 'left', unless='is_ready', after=['range_whole_left', 'runquery', 'check']) self.machine.add_transition('step', 'left', 'right', conditions='no_hits', after=['range_left_right', 'runquery', 'check']) self.machine.add_transition('step', 'left', 'whole', unless='is_ready', after=['range_shrink']) self.machine.add_transition('step', 'right', 'whole', unless='is_ready', after=['range_shrink']) elif self.kind == self.NEWEST: self.date_from = Arrow.fromdatetime(datetime.datetime(2000, 01, 01)) self.date_to = Arrow.utcnow() self.date_to += relativedelta(months=12-self.date_to.month, days=31-self.date_to.day) self.factor = -1 self.machine.add_transition('step', 'whole', 'right', unless='is_ready', after=['range_whole_right', 'runquery', 'check']) self.machine.add_transition('step', 'right', 'left', conditions='no_hits', after=['range_right_left', 'runquery', 'check']) self.machine.add_transition('step', 'right', 'whole', unless='is_ready', after=['range_shrink']) self.machine.add_transition('step', 'left', 'whole', unless='is_ready', after=['range_shrink']) else: raise ValueError('kind must be self.OLDEST or self.NEWEST') self.delta = (self.date_to - self.date_from) / 2
def validate_study_day_with_datetime( self, subject_identifier=None, study_day=None, compare_date=None, study_day_field=None, ): """Raises an exception if study day does not match calculation against pytz. Note: study-day is 1-based. """ if study_day is not None and compare_date is not None: try: compare_date = compare_date.date() except AttributeError: pass subject_identifier = (subject_identifier or self.cleaned_data.get("subject_identifier") or self.instance.subject_identifier) if not subject_identifier: raise ValueError( f"Subject identifier cannot be None. See {repr(self)}") registered_subject_model_cls = django_apps.get_model( "edc_registration.registeredsubject") randomization_datetime = registered_subject_model_cls.objects.get( subject_identifier=subject_identifier).randomization_datetime days_on_study = (compare_date - randomization_datetime.date()).days if study_day - 1 != days_on_study: tz = pytz.timezone(settings.TIME_ZONE) formatted_date = ( Arrow.fromdatetime(randomization_datetime).to(tz).strftime( convert_php_dateformat(settings.DATETIME_FORMAT))) message = { study_day_field: (f"Invalid. Expected {days_on_study + 1}. " f"Subject was registered on {formatted_date}") } print(message) self._errors.update(message) self._error_codes.append(INVALID_ERROR) raise forms.ValidationError(message, code=INVALID_ERROR)
def setUp(self): self.subject_identifier = '111111111' self.reference_helper = self.reference_helper_cls( visit_model='bcpp_subject.subjectvisit', subject_identifier=self.subject_identifier) report_datetime = Arrow.fromdatetime( datetime(2015, 1, 7)).datetime self.reference_helper.create_visit( report_datetime=report_datetime, timepoint='T0') self.reference_helper.create_visit( report_datetime=report_datetime + relativedelta(years=1), timepoint='T1') self.reference_helper.create_visit( report_datetime=report_datetime + relativedelta(years=2), timepoint='T2') self.subject_visits = LongitudinalRefset( name=self.visit_model, subject_identifier=self.subject_identifier, visit_model=self.visit_model, reference_model_cls=self.reference_model ).order_by('report_datetime')
def __init__(self, **kwargs): super().__init__(**kwargs) declined = None self.longitudinal_refset.order_by('hiv_result_datetime') hiv_result = None hiv_result_datetime = None for index, result in enumerate( self.longitudinal_refset.fieldset('hiv_result')): if result == POS: hiv_result = result hiv_result_datetime = self.longitudinal_refset.fieldset( 'hiv_result_datetime')[index] break if not hiv_result: # try to get the last NEG or DECLINED self.longitudinal_refset.order_by('-report_datetime') for index, result in enumerate( self.longitudinal_refset.fieldset('hiv_result')): if result in [DECLINED, NEG]: if result == DECLINED: declined = True hiv_result = result hiv_result_datetime = self.longitudinal_refset.fieldset( 'hiv_result_datetime')[index] break if not hiv_result: self.longitudinal_refset.order_by('report_datetime') hiv_result = self.longitudinal_refset.fieldset('hiv_result').last() hiv_result_datetime = self.longitudinal_refset.fieldset( 'hiv_result_datetime').last() self.values.update(hiv_result=hiv_result) self.values.update(hiv_result_datetime=hiv_result_datetime) self.values.update(today_hiv_result=hiv_result) if hiv_result_datetime: self.values.update(today_hiv_result_date=Arrow.fromdatetime( hiv_result_datetime).date()) else: self.values.update(today_hiv_result_date=None) self.values.update(declined=declined)
def label_context(self): edc_protocol_app_config = django_apps.get_app_config('edc_protocol') utc = Arrow.fromdatetime( self.requisition.drawn_datetime or self.requisition.created) dte = utc.to(settings.TIME_ZONE).datetime formatted_date = dte.strftime("%Y-%m-%d %H:%M") printed = 'PRINTED: ' if not self.requisition.drawn_datetime else 'DRAWN: ' return { 'requisition_identifier': self.requisition.requisition_identifier, 'item': self.item, 'item_count': self.requisition.item_count or 1, 'primary': '<P>', 'barcode_value': self.requisition.requisition_identifier, 'protocol': edc_protocol_app_config.protocol, 'site': str(self.requisition.site.id), 'site_name': str(self.requisition.site.name), 'clinician_initials': self.user.username[0:2].upper(), 'drawn_datetime': f'{printed}{formatted_date}', 'subject_identifier': self.registered_subject.subject_identifier, 'gender': self.registered_subject.gender, 'dob': self.registered_subject.dob, 'initials': self.registered_subject.initials, 'alpha_code': self.requisition.panel_object.alpha_code, 'panel': self.requisition.panel_object.abbreviation}
def load_time_cn(self, timestr) -> Arrow: d_time = datetime.datetime.strptime(timestr, r"%Y/%m/%d %H:%M:%S") a_time = Arrow.fromdatetime(d_time) if a_time.time() < datetime.time(hour=5): a_time -= datetime.timedelta(hours=5) return a_time
#!/usr/bin/env python from functools import reduce from base64 import urlsafe_b64encode from uuid import uuid4 from requests import Session from requests.adapters import HTTPAdapter from urllib.parse import urlparse, urlunparse from datetime import datetime, timedelta from arrow.arrow import Arrow dt_arrow = lambda dt: Arrow.fromdatetime(dt) from ics import Calendar as CalendarBase, Event from ics.timeline import Timeline import logging log = logging.getLogger('calenvite.calenvite') from calenvite.exceptions import ResourceNotFound, ResourceConflict DEFAULT_DOMAIN='localhost' class WebcalAdapter(HTTPAdapter): def get_connection(self, url, proxies=None): url = 'http'+url[6:] if url.startswith('webcal') else url return super().get_connection(url, proxies)
def date_iso(date): return Arrow.fromdatetime(date).format('YYYY-MM-DD')
def date_iso_compact(date): return Arrow.fromdatetime(date).format('YYYYMMDD')
def date_german(date): return Arrow.fromdatetime(date).format('DD.MM.YYYY')