def __init__(self, field, request, params, model, model_admin, field_path): self.field_generic = '%s__' % field_path self.date_params = { k: v for k, v in params.items() if k.startswith(self.field_generic) } now = jdatetime.datetime.fromgregorian(datetime=timezone.now()) if timezone.is_aware(now): now = timezone.localtime(now) if isinstance(field, models.jDateTimeField): today = now.replace(hour=0, minute=0, second=0, microsecond=0) else: today = now.date() tomorrow = today + jdatetime.timedelta(days=1) if today.month == 12: next_month = today.replace(year=today.year + 1, month=1, day=1) else: next_month = today.replace(month=today.month + 1, day=1) next_year = today.replace(year=today.year + 1, month=1, day=1) self.lookup_kwarg_since = '%s__gte' % field_path self.lookup_kwarg_until = '%s__lt' % field_path self.links = ( (_('Any date'), {}), (_('Today'), { self.lookup_kwarg_since: today.strftime('%Y-%m-%d %H:%M:%S'), self.lookup_kwarg_until: tomorrow.strftime('%Y-%m-%d %H:%M:%S'), }), (_('Past 7 days'), { self.lookup_kwarg_since: (today - jdatetime.timedelta(days=7)).strftime('%Y-%m-%d %H:%M:%S'), self.lookup_kwarg_until: tomorrow.strftime('%Y-%m-%d %H:%M:%S'), }), (_('This month'), { self.lookup_kwarg_since: (today.replace(day=1)).strftime('%Y-%m-%d %H:%M:%S'), self.lookup_kwarg_until: next_month.strftime('%Y-%m-%d %H:%M:%S'), }), (_('This year'), { self.lookup_kwarg_since: (today.replace(month=1, day=1)).strftime('%Y-%m-%d %H:%M:%S'), self.lookup_kwarg_until: next_year.strftime('%Y-%m-%d %H:%M:%S'), }), ) super(JDateFieldListFilter, self).__init__(field, request, params, model, model_admin, field_path)
def test_date_calculation_on_timedelta(self): date_1395 = jdatetime.date(1395,1,1) day_before = date_1395 - jdatetime.timedelta(days=1) day_after = date_1395 + jdatetime.timedelta(days=1) self.assertEqual(day_before, jdatetime.date(1394, 12, 29)) self.assertEqual(day_after, jdatetime.date(1395, 1, 2)) day_after = jdatetime.timedelta(days=1) + date_1395 self.assertEqual(day_before, jdatetime.date(1394, 12, 29)) self.assertEqual(day_after, jdatetime.date(1395, 1, 2))
def setUp(self): self.request_factory = RequestFactory() self.today = jdatetime.date.today() self.tomorrow = self.today + jdatetime.timedelta(days=1) self.one_week_ago = self.today - jdatetime.timedelta(days=7) if self.today.month == 12: self.next_month = self.today.replace(year=self.today.year + 1, month=1, day=1) else: self.next_month = self.today.replace(month=self.today.month + 1, day=1) self.next_year = self.today.replace(year=self.today.year + 1, month=1, day=1) #Bars self.mybartime = BarTime.objects.create(name="foo", datetime=self.today)
def last_week_user_total_sell(self, user, shop_slug): now = jdatetime.datetime.now() current_week_start_date = now - jdatetime.timedelta(days=4) last_week_start_date = current_week_start_date - jdatetime.timedelta( days=7) return self.filter( product__FK_Shop__FK_ShopManager=user, invoice__status=invoice_models.Invoice.Statuses.COMPLETED, invoice__created_datetime__gt=str( last_week_start_date.togregorian()), invoice__created_datetime__lt=str( current_week_start_date.togregorian()), product__FK_Shop__Slug=shop_slug,).aggregate( amont=Sum('product__Price'))
def resolve_permits(self, info, days=None): permits = self.permits() if days: today = jdatetime.date.today() start_date = today - jdatetime.timedelta(days) # qs = qs.filter(xpref_id__perm_date__gte=start_date) permits = permits.filter(perm_date__gte=start_date) data = [ SaleSummary( proforma_number=permit.number, permit_number=permit.perm_number, part_number=permit.number_td, customer_name=permit.req_id.customer.name, kw=permit.total_kw(), amount=permit.total_proforma_price_vat()['price_vat'], income=AmountPercentField( amount=permit.total_proforma_received()['received'], percent=permit.total_proforma_received() ['received_percent'], ), remaining=AmountPercentField( amount=permit.total_proforma_received()['remaining'], percent=permit.total_proforma_received() ['remaining_percent'])) for permit in permits ] return data
def resolve_perms_count(self, info, days=None): user_permits = self.permits() if days: today = jdatetime.date.today() start_date = today - jdatetime.timedelta(days) user_permits = user_permits.filter(perm_date__gte=start_date) return user_permits.count()
def kwjs(request): days = 30 if request.method == "POST": days = int(request.POST['days']) today = jdatetime.date.today() startDate = today + jdatetime.timedelta(-days) requests = ReqSpec.objects\ .filter(req_id__is_active=True, req_id__date_fa__gte=startDate, req_id__date_fa__lt=today)\ .values('req_id__date_fa').annotate(sum=Sum(F('kw') * F('qty'), output_field=FloatField())).order_by('req_id__date_fa') req_kw_dict = {str(x['req_id__date_fa']): x['sum'] for x in requests} proformas = PrefSpec.objects.filter(xpref_id__is_active=True, xpref_id__date_fa__gte=startDate, xpref_id__date_fa__lt=today)\ .values('xpref_id__date_fa').annotate(sum=Sum(F('price') * F('qty') * 1.09, output_field=FloatField()))\ .order_by('xpref_id__date_fa') proformas_amount_dict = { str(x['xpref_id__date_fa']): x['sum'] for x in proformas } payments = Payment.objects.filter(is_active=True, date_fa__gte=startDate, date_fa__lt=today)\ .values('date_fa').annotate(sum=Sum('amount'))\ .order_by('date_fa') payments_amnt_dict = {str(x['date_fa']): x['sum'] for x in payments} data = { 'reqs': req_kw_dict, 'proformas': proformas_amount_dict, 'payments': payments_amnt_dict, } return JsonResponse(data, safe=False)
def resolve_sales_qty(self, info, days=None): qs = self.sales_specs() if days: today = jdatetime.date.today() start_date = today - jdatetime.timedelta(days) qs = qs.filter(xpref_id__perm_date__gte=start_date) qty = self.sales_qty(qs) return qty
def __init__(self, field, request, params, model, model_admin, field_path): self.field_generic = '%s__' % field_path self.date_params = {k: v for k, v in params.items() if k.startswith(self.field_generic)} now = jdatetime.datetime.fromgregorian(datetime=timezone.now()) if timezone.is_aware(now): now = timezone.localtime(now) if isinstance(field, models.jDateTimeField): today = now.replace(hour=0, minute=0, second=0, microsecond=0) else: today = now.date() tomorrow = today + jdatetime.timedelta(days=1) if today.month == 12: next_month = today.replace(year=today.year + 1, month=1, day=1) else: next_month = today.replace(month=today.month + 1, day=1) next_year = today.replace(year=today.year + 1, month=1, day=1) self.lookup_kwarg_since = '%s__gte' % field_path self.lookup_kwarg_until = '%s__lt' % field_path self.links = ( (_('Any date'), {}), (_('Today'), { self.lookup_kwarg_since: str(today), self.lookup_kwarg_until: str(tomorrow), }), (_('Past 7 days'), { self.lookup_kwarg_since: str(today - jdatetime.timedelta(days=7)), self.lookup_kwarg_until: str(tomorrow), }), (_('This month'), { self.lookup_kwarg_since: str(today.replace(day=1)), self.lookup_kwarg_until: str(next_month), }), (_('This year'), { self.lookup_kwarg_since: str(today.replace(month=1, day=1)), self.lookup_kwarg_until: str(next_year), }), ) super(JDateFieldListFilter, self).__init__( field, request, params, model, model_admin, field_path)
def base_prefspec(days): prefspecs = PrefSpec.objects.filter(xpref_id__is_active=True, xpref_id__perm=True) if days: today = jdatetime.date.today() start_date = today - jdatetime.timedelta(days) print(start_date) prefspecs = prefspecs.filter(xpref_id__perm_date__gte=start_date) print(prefspecs.count()) return prefspecs
def shift_from(date=None): if not date: now = jdatetime.datetime.now().astimezone(pytz.timezone('Asia/Tehran')) if now.minute <= 15: now = now.replace(minute=15) elif now.minute <= 30: now = now.replace(minute=30) elif now.minute <= 45: now = now.replace(minute=45) else: now = now.replace(minute=59) + jdatetime.timedelta(minutes=1) end_date = now + jdatetime.timedelta(days=7) date_ = now else: date_ = date end_date = date + jdatetime.timedelta(days=1) work_shift = WorkShift.objects.first() usual_day_start_morning = work_shift.usual_day_start_morning usual_day_start_morning = jdatetime.time( hour=usual_day_start_morning.hour, minute=usual_day_start_morning.minute) usual_day_start_afternoon = work_shift.usual_day_start_afternoon usual_day_start_afternoon = jdatetime.time( hour=usual_day_start_afternoon.hour, minute=usual_day_start_afternoon.minute) usual_day_end_morning = work_shift.usual_day_end_morning usual_day_end_morning = jdatetime.time(hour=usual_day_end_morning.hour, minute=usual_day_end_morning.minute) usual_day_end_afternoon = work_shift.usual_day_end_afternoon usual_day_end_afternoon = jdatetime.time( hour=usual_day_end_afternoon.hour, minute=usual_day_end_afternoon.minute) shifts = [] last_shift = date_ while last_shift <= end_date: if usual_day_start_morning <= last_shift.time() < usual_day_end_morning or \ usual_day_start_afternoon <= last_shift.time() < usual_day_end_afternoon: shifts.append( last_shift.replace(second=0, microsecond=0).togregorian()) last_shift = last_shift + jdatetime.timedelta(minutes=15) return shifts
def get_first_date_of_month_in_specified_months_ago(num_of_month_ago: int, persian: bool = False): if num_of_month_ago == 1: return get_first_date_of_current_month() td = get_today_date() for m in range(num_of_month_ago): dlt = jdatetime.timedelta(days=td.day - ONE) td = td.__sub__(dlt) if persian: return td return td.togregorian()
def income_total(days): payments = Payment.objects.filter(is_active=True) if days: today = jdatetime.date.today() start_date = today - jdatetime.timedelta(days) print(start_date) payments = payments.filter(date_fa__gte=start_date) payment_amount = payments.aggregate(total=Sum('amount')) payment_amount = payment_amount['total'] payment_amount = 0 if not payment_amount else payment_amount return payment_amount
def agentjs(request): days = 30 if request.method == "POST": days = int(request.POST['days']) today = jdatetime.date.today() startDate = today + jdatetime.timedelta(-days) endDate = today + jdatetime.timedelta(1) agents_total_kw = ReqSpec.objects.values( 'req_id__customer', 'req_id__customer__name').filter(req_id__customer__agent=True).filter( req_id__date_fa__gte=startDate, req_id__date_fa__lt=endDate).distinct().annotate( sum=Sum(F('qty') * F('kw'), output_field=FloatField())) agenst_status_list = [{ 'customer_name': a['req_id__customer__name'], 'customer': a['req_id__customer'], 'kw': a['sum'], } for a in agents_total_kw] agent_data = {a['customer']: a for a in agenst_status_list} return JsonResponse(agent_data, safe=False)
def test_date_raise_exception_on_invalid_calculation(self): date_1395 = jdatetime.date(1395,1,1) with self.assertRaises(TypeError): day_before = date_1395 - 1 with self.assertRaises(TypeError): day_before = date_1395 + 1 with self.assertRaises(TypeError): day_before = jdatetime.timedelta(days=1) - date_1395 with self.assertRaises(TypeError): day_before = date_1395 + date_1395
def get_date_range(year, month) -> tuple: """Return the year for which this view should display data.""" format = "%Y-%m" datestr = f"{year}-{month}" start_date = jdatetime.datetime.strptime(datestr, format).date() end_date = start_date + jdatetime.timedelta(days=30) try: return start_date.togregorian(), end_date.togregorian() except ValueError: raise Http404( 'Invalid date string “%(datestr)s” given format “%(format)s”' % { 'datestr': datestr, 'format': format, })
def save(self, *args, **kwargs): if self.last_saturday and self.last_sunday and self.last_monday and self.last_tuesday and self.last_wednesday and self.last_thursday and self.last_friday: self.first_day_2 = self.last_day + timedelta(days=1) self.first_day = None self.last_day = None self.last_length = None self.last_saturday = False self.last_sunday = False self.last_monday = False self.last_tuesday = False self.last_wednesday = False self.last_thursday = False self.last_friday = False super(LastDataModel, self).save(*args, **kwargs)
def extract_chart(self, symbol, chart_name, end_date, time_slot): # the list representing the labels of a line chart x = [] # the list representing the data of a line chart y = [] # the return value (a tuple) d = None if time_slot == ONE_WEEK or time_slot == THREE_WEEK: # Considering a week has 7 days, we extract those rows from our database # that match the given symbol and time duration given as inputs to the method start_date = end_date - jdate.timedelta(days = time_slot*7) date = start_date while date <= end_date: t = 0 for row in self.datas: if row['date'] == date and symbol == row['symbol']: y.append(row[chart_name]) t = 1 break x.append(str(date)) if t == 0: y.append(0) date += jdate.timedelta(days = 1) d = (x, y) elif time_slot == THREE_MONTHS: end_date = self.set_to_wednesday(end_date) start_date = end_date - jdate.timedelta(days = 12*7) date = start_date while date <= end_date: sum_value = 0 for row in self.datas: if symbol == row['symbol'] and row['date'] > date and row['date'] <= date + jdate.timedelta(days = 7): sum_value = sum_value + row[chart_name] x.append(str(date + jdate.timedelta(days = 7))) y.append(sum_value) date += jdate.timedelta(days = 7) d = (x, y) elif time_slot == ONE_YEAR: start_date = jdate.date(end_date.year - 1, end_date.month, end_date.day) # print(str(start_date)+ 'تاریخ شروع ') # print(str(end_date) + 'تاریخ پایان ') date = start_date while date <= end_date: # print(str(date) + 'curr date') sum_value = 0 for row in self.datas: if symbol == row['symbol'] and row['date'].year == date.year and row['date'].month == date.month: sum_value = sum_value + row[chart_name] x.append(date.j_months_fa[date.month - 1]) y.append(sum_value) date += jdate.timedelta(days = 30) d = (x, y) return d
def test_comparison(self): today = jdatetime.date.today() self.assertEqual(False, today < today - jdatetime.timedelta(days=76)) self.assertEqual(False, today <= today - jdatetime.timedelta(days=1)) self.assertEqual(True, today + jdatetime.timedelta(days=1) > today) self.assertEqual(True, today + jdatetime.timedelta(days=30) >= today) self.assertEqual(True, today == today) not_today = jdatetime.date(today.year, today.month, today.day) + jdatetime.timedelta(days=1) self.assertEqual(True, today != not_today) dtg = jdatetime.datetime(1380, 12, 1, 1, 2, 4) self.assertEqual(True, dtg < dtg + jdatetime.timedelta(seconds=1)) self.assertEqual(True, dtg - jdatetime.timedelta(seconds=1) < dtg) self.assertEqual(False, dtg is None)
def __init__(self, f, request, params, model, model_admin, field_path=None): super(jDateFieldFilterSpec, self).__init__(f, request, params, model, model_admin, field_path=field_path) self.field_generic = '%s__' % self.field_path self.date_params = dict([(k, v) for k, v in params.items() if k.startswith(self.field_generic)]) today = jdatetime.date.today() one_week_ago = today - jdatetime.timedelta(days=7) #today_str = isinstance(self.field, jmodels.DateTimeField) \ # and today.strftime('%Y-%m-%d 23:59:59') \ # or today.strftime('%Y-%m-%d') today_str = today.strftime('%Y-%m-%d') last_day_this_month = 29 if today.month == 12 and today.isleap() : last_day_this_month = 30 else : last_day_this_month= jdatetime.j_days_in_month[today.month-1] last_day_this_year = 29 if today.isleap() : last_day_this_year = 30 self.links = ( (_('Any date'), {}), (_('Today'), {'%s' % self.field_path: today.strftime('%Y-%m-%d')}), (_('Past 7 days'), {'%s__gte' % self.field_path: one_week_ago.strftime('%Y-%m-%d'), '%s__lte' % self.field_path: today_str}), (_('This month'), {'%s__gte' % self.field_path: today.replace(day=1).strftime('%Y-%m-%d'), '%s__lte' % self.field_path: today.replace(day=last_day_this_month).strftime('%Y-%m-%d')}), (_('This year'), {'%s__gte' % self.field_path: today.replace(day=1,month=1).strftime('%Y-%m-%d'), '%s__lte' % self.field_path: today.replace(day=last_day_this_year, month=12).strftime('%Y-%m-%d')} ) )
def dst(self, dt): return jdatetime.timedelta(0)
def utcoffset(self, dt): return jdatetime.timedelta(hours=3, minutes=30)
def utcoffset(self, dt): return jdatetime.timedelta(hours=0)
def set_to_wednesday(self, date): while date.weekday() != 4: date += jdate.timedelta(days = 1) return date