def leavebookconfirm(request, pk, loc): template_name = 'pages/leavebookconfirm.html' book = get_object_or_404(Book, pk=pk) location = get_object_or_404(Location, pk=loc) custom_loc = location.location.split(',') newloc = '' for l in custom_loc: if l == ' Tehran': newloc = newloc + l break newloc = newloc + l + ',' time = datetime.now() if request.method == 'POST': user_book = get_object_or_404(User_Book, book=book, user=request.user, address=None) user_book.address = location user_book.release_date = datetime.now() user_book.save() return redirect('books:booklist') return render(request, template_name, { 'book': book, 'location': location, 'time': time, 'loc': newloc })
def bookhistory(request): template_name = 'bookhistory.html' field = request.GET.get('field') book = get_object_or_404(Book, BID=field) check = User_Book.objects.filter(book=book, address=None) print(check) if not check: user_book = User_Book(user=request.user, book=book, address=None, release_date=datetime.now()) user_book.save() record = User_Book.objects.select_related('book').filter( book__BID=field).order_by('release_date').reverse() record = list(record) for counter in range(0, len(record)): location = [] if record[counter].address: location = record[counter].address.location location = location.split(',') newloc = '' for l in location: if l == ' Tehran': newloc = newloc + l break newloc = newloc + l + ',' record[counter] = (record[counter], counter % 2, newloc) return render(request, template_name, {'record': record, 'book': book})
def confirmlocation(request, pk, loc): template_name = 'pages/confirmlocation.html' book = Book.objects.get(pk=pk) location = Location.objects.get(pk=loc) custom_loc = location.location.split(',') newloc = '' for l in custom_loc: if l == ' Tehran': newloc = newloc + l break newloc = newloc + l + ',' if request.method == 'POST': user = request.user user_book = User_Book(user=user, book=book, address=location, release_date=datetime.now()) user_book.save() return redirect('books:booklist') return render(request, template_name, { 'book': book, 'location': location, 'loc': newloc })
def main(): if len(sys.argv) < 2: print('not enough arguments') sys.exit(1) action = sys.argv[1] if action == 'generate': if len(sys.argv) <= 2: print('symbol id was not provided') sys.exit(1) symbol_id = sys.argv[2] if len(sys.argv) > 3: start_time = jdatetime.strptime(sys.argv[3], '%Y-%m-%d') else: start_time = jdatetime(1396, 1, 1) if len(sys.argv) > 4: end_time = jdatetime.strptime(sys.argv[4], '%Y-%m-%d') else: end_time = jdatetime.now() generate(symbol_id=symbol_id, start_time=start_time, end_time=end_time) elif action == 'install': if len(sys.argv) <= 2: print('file location was not provided') sys.exit(1) file_location = sys.argv[2] install(file_location=file_location) else: print('invalid action') sys.exit(1)
def calendar(): date = datetime.now() new_day = ''.join( [str(settings.PERSIAN_NUM[int(i)]) for i in str(date.day)]) new_mon = settings.JALALI_CAL[date.month] new_year = ''.join( [str(settings.PERSIAN_NUM[int(i)]) for i in str(date.year)]) return '%s %s %s' % (new_day, new_mon, new_year)
def dateTime(self): self.tz = timezone('Asia/Tehran') self.TimeSabt = dt.now(self.tz) self.nowYear = self.TimeSabt.strftime("%Y") self.nowMonth = self.TimeSabt.strftime("%m") self.nowDay = self.TimeSabt.strftime("%d") self.nowHour = self.TimeSabt.strftime("%H") self.nowMinute = self.TimeSabt.strftime("%M")
def get_datetime(frmt: str): ## {{{ from datetime import datetime as dt from jdatetime import datetime as jdt if frmt == 'ymdhms': output = dt.now().strftime('%Y%m%d%H%M%S') elif frmt == 'ymd': output = dt.now().strftime('%Y%m%d') elif frmt == 'hms': output = dt.now().strftime('%H%M%S') elif frmt == 'seconds': output = dt.now().strftime('%s') elif frmt == 'weekday': output = dt.now().strftime('%A') elif frmt == 'jymdhms': output = jdt.now().strftime('%Y%m%d%H%M%S') elif frmt == 'jymd': output = jdt.now().strftime('%Y%m%d') elif frmt == 'jhms': output = jdt.now().strftime('%H%M%S') elif frmt == 'jseconds': output = int( jdt.now().timestamp() ) ## exceptionally written in this format. have to use int to get rid of decimals elif frmt == 'jweekday': output = jdt.now().strftime('%A') return output
def get_date() -> dict: """ Gets today month and day in Miladi & Shamsi from your local timezone :returns -> Miladi & Shamsi month-day in a dict """ today = datetime.now() j_today = jdatetime.now() return { 'month': str(today.strftime("%B")), 'day': str(today.day), 'jmonth': str(j_today.strftime("%B")), 'jday': str(j_today.day) }
def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): obj = Duties() obj.Subject = form.cleaned_data['Subject'] obj.Content = form.cleaned_data['Content'] obj.DutySender = self.request.user.familymemberstbl obj.DutyReceiver = form.cleaned_data['DutyReceiver'] obj.Priority = form.cleaned_data['Priority'] obj.CreateDate = jd.now().strftime("%d-%m-%Y %I:%M") obj.DeadLineDate = form.cleaned_data['DeadLineDate'] obj.CheckStatus = CheckingStatuses.objects.get(id=1) obj.save() messages.add_message(request, messages.SUCCESS, 'درخواست جدید با موفقیت درج شد') return HttpResponseRedirect('/home/')
def index_view(request): last5output = Storage.objects.all().filter(complete=True)[:5] progress = Storage.objects.all().filter(complete=False).filter(final__gt=date.today() - timedelta(days=2))[:5] if request.POST: form = CustomForm(request.POST) if form.is_valid(): data = form.cleaned_data name = "Output_{}".format(str(datetime.now()).split('.')[-2]) path = name + '.xlsx' s = Storage(name=name, complete=False, address=path, starter=request.user) s.save() crawler_engine.delay(output_name=name, sites=data["sites"], users=data["users"]) messages.success(request, "فرآیند آغاز شد") return redirect('index') else: form = CustomForm() return render(request=request, template_name='index.html', context={'items': last5output, 'progress': progress, 'form': form})
class BotStats: date = datetime.now(timezone('Asia/Tehran')).strftime('%Y-%m-%d %H:%M:%S') roles_set = 0 lists_updated = 0 lists_requested = 0 shekars_set = 0 votes_saved = 0 votes_said = 0 equal_votes = 0 my_state = 0 gpstate = 0 panel_emoji = 0 most_roles = 0 most_roles_detailed = 0 most_votes = 0 most_roles_pv = 0 sc = 0 rc = 0 cultup = 0 myafks = 0 set_lang = 0
def refresh_sms_token(): token_headers = {"Content-Type": "application/json"} token_data = { "UserApiKey": settings.SMS_IR['USER_API_KEY'], "SecretKey": settings.SMS_IR['SECRET_KEY'] } try: r = post(settings.SMS_IR['TOKEN_KEY_URL'], dumps(token_data), headers=token_headers) response = loads(r.text) if response['IsSuccessful'] is True: config.ACTIVE_TOKEN_KEY = response['TokenKey'] config.LAST_UPDATE = datetime.now() return 'Token key is {}'.format(response['TokenKey']) else: print('token_key sms.ir error {}'.format(response['Message'])) return False except Exception as e: print('token_key sms.ir error {}'.format(e)) return False
def __init__(self, *args, **kwargs): """FirstPage constructor.""" super().__init__(*args, **kwargs) self.ui = Ui_first_page() self.ui.setupUi(self) # Connecting the buttons to open Sign in and Sign out pages self.ui.first_page_sign_in_button.clicked.connect( self.open_sign_in_page) self.ui.first_page_sign_up_button.clicked.connect( self.open_sign_up_page) # Set the date and time label to show the current date and time t1 = datetime.now() date_and_time = "<%s %s %s> - <%s:%s %s>." % (t1.day, t1.strftime( "%B"), t1.year, t1.strftime("%I"), t1.minute, t1.strftime("%p")) self.ui.first_page_date_and_time_Label.setText(date_and_time) self.ui.layoutWidget.adjustSize() self.show()
from django import forms from django.forms import ModelForm from app_accounts.models import Profile from jdatetime import datetime from django.core.exceptions import ValidationError now = datetime.now() YEARS = [(i, i) for i in range(1330, now.year + 1)] MONTHS = [(i + 1, j) for i, j in enumerate(now.j_months_fa)] DAYS = [(day, day) for day in range(1, 32)] def check_phone_num(value): if not value.isdigit(): raise ValidationError('لطفا یه شماره موبایل معتبر وارد کن!') def check_phone_num_len(value): if not (11 <= len(value) <= 13): raise ValidationError('طول شماره مبایل نامعتبر است!') def check_year(value): if int(value) > now.year: raise ValidationError('لطفا یه سال معتبر وارد کن!') class ProfileForm(ModelForm):
def __init__(self, name: str, mode='r') -> None: self.start = datetime.now() self.file = open(name, mode)
def __exit__(self, exc_type, exc_val, exc_tb): self.file.write(self.start, datetime.now()) return True
def save(self, order): # get settings settings = s.get('invoices') # current date and time in jalali calendar date_frmt = '%Y/%m/%d' time_frmt = '%H:%M:%S' current_date = jdatetime.now().date().strftime(date_frmt) current_time = jdatetime.now().date().strftime(time_frmt) # order date and time in jalali calendar order_datetime = jdatetime.fromgregorian( datetime=order['created_date']) order_date = order_datetime.date().strftime(date_frmt) order_time = order_datetime.time().strftime(time_frmt) # detect customer if not order['customer_id']: customer_id = settings['guest'] else: try: customer_map = self.customer_map.get(wcid=order['customer_id']) customer_id = customer_map.id except DoesNotExists: self.customer.create({ 'Code': self.customer.max('Code') + 1, 'Fname': order['first_name'], 'LName': order['last_name'], 'Name': '{} {}'.format(order['first_name'], order['last_name']), 'BuyPriceLevel': settings['price_level'], 'SellPriceLevel': settings['price_level'], 'StartDate': current_date, 'Prefix': '', 'ShiftTo': '23:59:59', 'ShiftFrom': '00:00:00', 'Visitor': 0, 'CarryPrice': 0, 'VisitorBed': 0, 'EtebarNaghd': 0, 'VisitorPerc': 0, 'EtebarCheque': 0, 'MablaghAvalDore': 0, }) customer_id = self.customer.max('ID') self.customer_map.create({ 'id': customer_id, 'wcid': order['customer_id'], 'last_update': datetime.now() }) # get next invoice No invoice_no = self.invoice.custom_sql("SELECT dbo.NewFactorNo(?)", [settings['type']], method='fetchval') # prepare invoice fields fields = { 'FactorNo': invoice_no, 'FishNo': invoice_no, 'Type': settings['type'], 'IDShakhs': customer_id, 'UserID': 1, 'Date': order_date, 'Time': order_time, 'PaymentDate': order_date, 'DeliverDate': order_date, 'InsertDate': current_date, 'InsertTime': current_time, 'Info': '', 'JamKol': int(order['total']), 'GmeFactor': order['items_subtotal'], 'MandeFactor': int(order['total']), 'Maliat': int(order['total_tax']), 'Takhfif': order['discount'], 'TakhfifItem': order['items_discount'], 'CarryPrice': int(order['shipping_total']), 'CarryType': 0, 'Nagd': 0, 'Nagd2': 0, 'Naseh': 0, 'Naseh2': 0, 'Chek': 0, 'Chek2': 0, 'Anbar': 0, 'Confirmed': 0, 'VisitorPrice': 0, 'VisitorPerc': 0, 'PaymentValue': 0, 'PaymentType': 0, 'Tmp': 0, 'Converted': 0, 'MaliatPerc': 0, 'ServicePerc': 0, 'ServicePrice': 0 } # check for info if fields['CarryPrice']: fields['Info'] = _('carry price: {}').format(fields['CarryPrice']) # create invoice self.invoice.create(fields) invoice_id = self.invoice.max('ID') # insert items for i, item in enumerate(order['items'], 1): self.line_item.create({ 'FactorID': invoice_id, 'IDKala': item['id'], 'Tedad': item['quantity'], 'Tedad1': 0, 'Tedad2': item['quantity'], 'TedadStr': str(item['quantity']), 'Price': item['regular_price'], 'SumPrice': int(item['total']), 'Takhfif': item['discount'], 'TakhfifPerc': 0, 'TakhfifPerItem': 0, 'TakhfifIsGift': 0, 'Anbar': settings['repository'], 'Info': '', 'Row': i, 'VisitorPrice': 0, 'VisitorPerc': 0, 'PaymentValue': 0, 'PaymentType': 0, 'PaymentDate': order_date, 'JozDarKol': 0, 'Maliat': 0, 'Height': 0, 'Width': 0, 'Thick': 0, 'Density': 0, 'UnitType': 0, 'Amount': 0, 'Overhead': 0, 'Gift': 0, 'Value': 0, 'PriceLevelID': settings['price_level'], 'ValueEdited': 0 }) # create map self.invoice_map.create({ 'id': invoice_id, 'wcid': order['id'], 'last_update': datetime.now() })
def home(request): current_month = datetime.now() #TODO current is today not month fix this last_month = datetime.today() - timedelta(days=30) print(last_month) labels = [] data = [] queryset = exp.objects.filter(date__gt=last_month).order_by('-amount')[:6] for temp in queryset: labels.append(temp.title) data.append(temp.amount) USER = request.user INCOME = income.objects.filter(date__gt=last_month, user=USER).aggregate( Count('amount'), Sum('amount')) EXPENT = exp.objects.filter(date__gt=last_month, user=USER).aggregate(Count('amount'), Sum('amount')) expSum = EXPENT['amount__sum'] incoSum = INCOME['amount__sum'] exp_per = 0 inco_per = 0 if EXPENT['amount__count'] is not 0 and EXPENT[ 'amount__sum'] is not None and INCOME[ 'amount__count'] is not 0 and INCOME['amount__sum'] is not None: exp_per = ((EXPENT['amount__sum']) * 100) / INCOME['amount__sum'] inco_per = (100 - exp_per) statExpense = exp.objects.order_by('-date') statIncome = income.objects.order_by('-date') if request.method == 'POST': if request.POST.get('expent') and request.POST.get( 'amount1') and request.POST.get('date1'): expent = exp() expent.title = request.POST.get('expent') expent.amount = request.POST.get('amount1') expent.date = request.POST.get('date1') expent.user = request.user expent.save() return redirect('home') elif request.POST.get('income') and request.POST.get( 'amount2') and request.POST.get('date2'): inco = income() inco.title = request.POST.get('income') inco.amount = request.POST.get('amount2') inco.date = request.POST.get('date2') inco.user = request.user inco.save() return redirect('home') elif request.POST.get('T-date'): statExpense = exp.objects.filter( date__gt=request.POST.get('T-date')) statIncome = income.objects.filter( date__gt=request.POST.get('T-date')) return render( request, 'add.html', { 'username': request.user, 'labels': labels, 'data': data, 'expSum': expSum, 'incoSum': incoSum, 'expent': exp_per, 'income': inco_per, 'expStat': statExpense, 'incoStat': statIncome }) else: return render( request, 'add.html', { 'username': request.user, 'labels': labels, 'data': data, 'expSum': expSum, 'incoSum': incoSum, 'expent': exp_per, 'income': inco_per, 'expStat': statExpense, 'incoStat': statIncome })
def __init__(self, price): self.price = price self.time = datetime.now(tz).strftime('%Y-%m-%d %H:%M:%S')