def test_others(self): self.assertTrue( JalaliDateTime.fromtimestamp(time.time() - 10) <= JalaliDateTime.now()) self.assertEqual( JalaliDateTime(1367, 2, 14, 4, 30, 0, 0, pytz.utc).timestamp(), 578723400) self.assertEqual( JalaliDateTime.fromtimestamp(578723400, pytz.utc), JalaliDateTime(1367, 2, 14, 4, 30, 0, 0, pytz.utc), ) self.assertEqual( JalaliDateTime(1367, 2, 14, 4, 30, 4, 4444).jdate(), JalaliDate(1367, 2, 14)) self.assertEqual( JalaliDateTime(1367, 2, 14, 4, 30, 4, 4444).date(), date(1988, 5, 4)) self.assertEqual( JalaliDateTime(1367, 2, 14, 4, 30, 0, 0).replace(tzinfo=pytz.utc).__repr__(), "JalaliDateTime(1367, 2, 14, 4, 30, tzinfo=<UTC>)", ) self.assertEqual( JalaliDateTime(1367, 2, 14, 4, 30, 4, 4444).replace(year=1395, day=3, minute=59), JalaliDateTime(1395, 2, 3, 4, 59, 4, 4444), ) self.assertEqual(JalaliDateTime.now(pytz.utc).tzname(), "UTC") self.assertIsNone(JalaliDateTime.today().tzname()) self.assertIsNone(JalaliDateTime.today().dst()) self.assertEqual( JalaliDateTime(1367, 2, 14, 4, 30, 0, 0).ctime(), "Chaharshanbeh 14 Ordibehesht 1367 04:30:00", ) self.assertEqual( JalaliDateTime(1396, 7, 27, 21, 48, 0, 0).ctime(), "Panjshanbeh 27 Mehr 1396 21:48:00", ) self.assertEqual( JalaliDateTime(1367, 2, 14, 4, 30, 0, 0).replace(locale="fa").ctime(), "چهارشنبه ۱۴ اردیبهشت ۱۳۶۷ ۰۴:۳۰:۰۰", ) self.assertEqual( JalaliDateTime(1397, 12, 1, 23, 32, 0, 0).replace(locale="fa").ctime(), "چهارشنبه ۰۱ اسفند ۱۳۹۷ ۲۳:۳۲:۰۰", ) self.assertEqual( JalaliDateTime(1367, 2, 14, 4, 30, 0, 1, pytz.utc).isoformat(), "1367-02-14T04:30:00.000001+00:00", ) self.assertEqual( JalaliDateTime(1367, 2, 14, 4, 30, 0, 1, pytz.utc).__str__(), "1367-02-14 04:30:00.000001+00:00", )
def test_others(self): self.assertTrue(JalaliDateTime.fromtimestamp(time.time()) <= JalaliDateTime.now()) self.assertEqual(JalaliDateTime(1367, 2, 14, 4, 30, 0, 0, pytz.utc).timestamp(), 578723400) self.assertEqual(JalaliDateTime.fromtimestamp(578723400, pytz.utc), JalaliDateTime(1367, 2, 14, 4, 30, 0, 0, pytz.utc)) self.assertEqual(JalaliDateTime(1367, 2, 14, 4, 30, 4, 4444).jdate(), JalaliDate(1367, 2, 14)) self.assertEqual(JalaliDateTime(1367, 2, 14, 4, 30, 4, 4444).date(), date(1988, 5, 4)) self.assertEqual(JalaliDateTime(1367, 2, 14, 4, 30, 0, 0).replace(tzinfo=pytz.utc).__repr__(), 'JalaliDateTime(1367, 2, 14, 4, 30, tzinfo=<UTC>)') self.assertEqual(JalaliDateTime(1367, 2, 14, 4, 30, 4, 4444).replace(year=1395, day=3, minute=59), JalaliDateTime(1395, 2, 3, 4, 59, 4, 4444)) self.assertEqual(JalaliDateTime.now(pytz.utc).tzname(), "UTC") self.assertIsNone(JalaliDateTime.today().tzname()) self.assertIsNone(JalaliDateTime.today().dst()) self.assertEqual(JalaliDateTime(1367, 2, 14, 4, 30, 0, 0).ctime(), "Chaharshanbeh 14 Ordibehesht 1367 04:30:00") self.assertEqual(JalaliDateTime(1396, 7, 27, 21, 48, 0, 0).ctime(), "Panjshanbeh 27 Mehr 1396 21:48:00") self.assertEqual(JalaliDateTime(1367, 2, 14, 4, 30, 0, 0).replace(locale="fa").ctime(), "چهارشنبه ۱۴ اردیبهشت ۱۳۶۷ ۰۴:۳۰:۰۰") self.assertEqual(JalaliDateTime(1367, 2, 14, 4, 30, 0, 1, pytz.utc).isoformat(), "1367-02-14T04:30:00.000001+00:00") self.assertEqual(JalaliDateTime(1367, 2, 14, 4, 30, 0, 1, pytz.utc).__str__(), "1367-02-14 04:30:00.000001+00:00")
def lead_add(request): if request.method == "POST" and request.user.is_authenticated \ and request.user.is_staff: name_and_family = request.POST['name_and_family'] gender = request.POST['gender'] phone_fa = digits.ar_to_fa(request.POST['phone_number']) phone_en = digits.fa_to_en(phone_fa) register_status = request.POST['register_status'] operator = request.user origin = Origin.objects.filter(id=int(request.POST['origin'])).first() #fields should be validate if len(name_and_family) > 2 and len(phone_en) > 5 and len(phone_en) < 16 and\ phone_en.isdigit() and len(Lead.objects.filter(phone_number=phone_en)) == 0: lead = Lead(origin = origin, name_and_family = name_and_family.encode("utf-8"), gender = gender,\ phone_number = phone_en, register_status = register_status,\ led_time = datetime.now(),led_time_jalali = JalaliDateTime.now().strftime("%Y-%m-%d %H:%M:%S"),\ led_time_jalali_str = JalaliDateTime.now().strftime("%c")) #if lead is registered save operator if register_status == "K": lead.registered_by = request.user else: lead.registered_by = None lead.save() lead.operator.add(operator) messages.success(request, "You'r new lead has been save") return HttpResponseRedirect(request.META.get('HTTP_REFERER')) #if same phone number added by 1 or more operators elif len(Lead.objects.filter(phone_number=phone_en)) == 1: lead = Lead.objects.filter(phone_number=phone_en).first() if request.user in lead.operator.all(): messages.warning(request, "Phone number is repetitive") return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: if lead.register_status != "K": lead.operator.add(request.user) lead.save() messages.info(request, "lead is repetitive but you added to this lead operators") messages.success(request, "You'r new lead has been save") return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: messages.info(request, "lead is repetitive and registered by another operator") messages.warning(request, "You'r new lead did not changed!") return HttpResponseRedirect(request.META.get('HTTP_REFERER')) elif len(name_and_family) <= 3: messages.warning(request, "Check name and family fileld") return HttpResponseRedirect(request.META.get('HTTP_REFERER')) elif len(phone_en) <= 6 and len(phone_en) >= 16 and phone_en.isdigit() is False: messages.warning(request, "Phone number is in wrong format") return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: messages.warning(request, "something went wrong") return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: messages.error(request, "You'r not authorized") return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
def check_time(): today = JalaliDateTime.now().strftime('%m-%d') today = time.strptime(today, '%m-%d') a = '0' b = '0' c = 0 missings = db.execute('SELECT day, month FROM days WHERE in_time = ? AND off = ?', (a, c)).fetchall() print ("you have missing time entris in these days:") for missing in missings: m_d = str(missing[0]).zfill(2) m_m = str(missing[1]).zfill(2) day = f'{m_m}-{m_d}' day = time.strptime(day, '%m-%d') if today < day: break else: print (f'{m_m}-{m_d} Has no ENTER time') missings = db.execute('SELECT day, month FROM days WHERE out_time = ? AND off = ?', (b, c)).fetchall() print ("-------------------------------") for missing in missings: m_d = str(missing[0]).zfill(2) m_m = str(missing[1]).zfill(2) day = f'{m_m}-{m_d}' day = time.strptime(day, '%m-%d') if today < day: break else: print (f'{m_m}-{m_d} Has no EXIT time')
def fetch_startup_service(owner, context): """get the startup that assign to the requested user and get the custom leader that added by user Arguments: owner {OBEJCET} -- requested user context {DICT} -- a dictionary of context to add it some more context Returns: OBJECT -- returns the determined startup """ db_startup = get_startup_service(owner=owner) the_time = JalaliDateTime.now().to_gregorian() try: user_mentor = get_startup_service(owner=owner, rahbar__mentor_user=True) except: user_mentor = None context.update({ 'the_time': the_time, 'user_mentor': user_mentor, 'db_startup': db_startup, }) return db_startup
def test_base(self): self.assertEqual(JalaliDateTime(1367, 2, 14, 14, 0, 0, 0), JalaliDateTime.to_jalali(datetime(1988, 5, 4, 14, 0, 0, 0))) self.assertEqual(JalaliDateTime(1369, 7, 1, 14, 14, 1, 1111), JalaliDateTime(datetime(1990, 9, 23, 14, 14, 1, 1111))) self.assertEqual(JalaliDateTime(1369, 7, 1, 14, 14, 1, 9111), JalaliDateTime(JalaliDateTime(1369, 7, 1, 14, 14, 1, 9111))) g = JalaliDateTime.now() self.assertEqual(g.time(), _time(g.hour, g.minute, g.second, g.microsecond)) g = g.replace(tzinfo=pytz.timezone("America/Los_Angeles")) self.assertEqual(g.timetz(), _time(g.hour, g.minute, g.second, g.microsecond, pytz.timezone("America/Los_Angeles"))) self.assertEqual(JalaliDateTime.fromtimestamp(578723400, pytz.utc), JalaliDateTime(1367, 2, 14, 4, 30, 0, 0, pytz.utc)) self.assertEqual(JalaliDateTime.utcfromtimestamp(578723400), JalaliDateTime(1367, 2, 14, 4, 30, 0, 0)) try: JalaliDateTime._check_time_fields(20, 1, 61, 1000) except ValueError: assert True else: assert False try: JalaliDateTime._check_time_fields("20", 1, 61, 1000) except TypeError: assert True else: assert False
def export_all(request): leads = Lead.objects.order_by('-id') comments = Comment.objects.all() labels = Label.objects.all() time = JalaliDateTime.now().strftime("%H:%M %Y-%m-%d") data = {'comments': comments, 'leads':leads, 'labels': labels, 'time': time} return render(request,'leads/export/export_all.html', data)
async def job(): async with aiohttp.ClientSession() as session: start_time = time() async with session.get(url) as response: status = response.status response_body = await response.text() print('%s: Pinged %s / %.2fms / %d: %s' % (JalaliDateTime.now(timezone('Iran')).strftime('%Y-%m-%d %H:%M:%S%Z'), REMOTE_HOST, time() - start_time, status, response_body))
def comment_add(request): if request.method == "POST" and request.user.is_authenticated \ and request.user.is_staff and len(request.POST['text']) > 0: get_object_or_404(Lead, id=int(request.POST["id"])) post = Lead.objects.filter(id=int(request.POST["id"])).first() author = request.user text = request.POST['text'] comment = Comment(post = post, author = author, text = text, created_date = datetime.now(), \ created_date_jalali = JalaliDateTime.now().strftime("%Y-%m-%d %H:%M:%S"), \ created_date_jalali_str = JalaliDateTime.now().strftime("%c")) comment.save() messages.success(request, "You'r comment has been save") return HttpResponseRedirect(request.META.get('HTTP_REFERER')) elif len(request.POST['text']) == 0: messages.warning(request, "You'r comment text field is empty") return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: messages.error(request, "You'r not authorized") return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
def jdatetime(value, arg=""): try: if str(value) == "now": if arg == "": arg = "%Y-%m-%d %H:%M:%S" resultdate = JalaliDateTime.now() elif str(value) == "time": if arg == "": arg = "%H:%M:%S" resultdate = JalaliDateTime.now() elif str(value) == "date": if arg == "": arg = "%Y-%m-%d" resultdate = JalaliDateTime.now() else: if isinstance(value, datetime.date): resultdate = JalaliDateTime.to_jalali(value) else: year, month, day = map(int, value[:10].split('-')) hour = minute = second = millisecond = 0 if value.find(' ') == 10: date, time = value.split(' ') time = time.split(':') if len(time) == 1: hour = int(time[0]) elif len(time) == 2: hour = int(time[0]) minute = int(time[1]) elif len(time) == 3: hour = int(time[0]) minute = int(time[1]) time = time[2].split('.') second = int(time[0]) if len(time) > 1: millisecond = int(time[1]) resultdate = JalaliDateTime.to_jalali( datetime.datetime(year, month, day, hour, minute, second, millisecond)) if arg: return resultdate.strftime(arg) else: return resultdate except Exception as err: return "jdatetime error:%s" % err
def label_add(request): if request.method == "POST" and request.user.is_authenticated \ and request.user.is_staff: get_object_or_404(Lead, id=int(request.POST["lead_id"])) get_object_or_404(LabelDefinition, id=int(request.POST["label"])) #if label is uniqe for this lead if len(Label.objects.filter(label__id=int(request.POST["label"]), post__id=int(request.POST["lead_id"]))) == 0: post = Lead.objects.filter(id=int(request.POST["lead_id"])).first() label1 = LabelDefinition.objects.filter(id=int(request.POST["label"])).first() label = Label(post = post, label = label1, owner = request.user , created_date = datetime.now(), \ created_date_jalali = JalaliDateTime.now().strftime("%Y-%m-%d %H:%M:%S"), \ created_date_jalali_str = JalaliDateTime.now().strftime("%c")) label.save() messages.success(request, "You'r label has been changed") return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: messages.warning(request, "This label exist") return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: messages.error(request, "You'r not authorized") return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
def test_pickle(self): file = open("save.p", "wb") now = JalaliDateTime.now().replace(tzinfo=pytz.timezone("Asia/Tehran")) pickle.dump(now, file) file.close() file2 = open("save.p", "rb") j = pickle.load(file2) file2.close() self.assertEqual(j, now) os.remove("save.p")
def dashboard_chart_service(investor ,coach ,leader ,referee ,operational, track_info): """get the numbers of karmand an the current year of chart Arguments: investor {OBJECT} -- the role of investor coach {OBJECT} -- the role of coach leader {OBJECT} -- the role of leader referee {OBJECT} -- the role of referee operational {OBJECT} -- the role of operational Returns: DICT -- returns the current year and all monthes of jalali and numbers of karmands """ all_investorses = models.User.objects.filter(role=investor).count() all_startupses = StartUp.objects.all().count() all_coaches = models.User.objects.filter(role=coach).count() all_leaderes = models.User.objects.filter(role=leader).count() all_operationales = models.User.objects.filter( role=operational).count() all_referees = models.User.objects.filter(role=referee).count() th_year = JalaliDateTime.now().year chart = (StartUp.objects.filter(created_date__range=[get_date_jalali(int(th_year), month+1, 1), get_date_jalali(int(th_year), month+1, 31)]).count() for month in range(12)) monthes = [] for _ in range(12): monthes.append(chart.__next__()) status = "وارد پنل مدیریت شد" status_of_user(track_info, status, 'import-dashboard-administrator') return { 'farvardin': monthes[0], 'ordi': monthes[1], 'khurdad': monthes[2], 'tir': monthes[3], 'mordad': monthes[4], 'shahrivar': monthes[5], 'mehr': monthes[6], 'aban': monthes[7], 'azar': monthes[8], 'daaay': monthes[9], 'bahman': monthes[10], 'esfand': monthes[11], 'th_year': th_year, "all_investorses": all_investorses, "all_startupses": all_startupses, "all_coaches": all_coaches, "all_leaderes": all_leaderes, "all_operationales": all_operationales, "all_referees": all_referees}
def _send_user_timesheet(user): j_now = JalaliDateTime.now() receiver_email = settings.TIMESHEETS_RECEIVER_EMAIL if not receiver_email: raise ValueError("No receiver email address.") if not user.email: logging.info( f"User ({user.username}) email not found. Emailing the corresponding timesheet ignored." ) return cc_list = [] if user.email: cc_list.append(user.email) if user.detail.manager_email: cc_list.append(user.detail.manager_email) body_text = f'''Hello, Here is the timesheet of a user at SahaBee. This email is sent automatically by SahaBee, since the user was actively rollcalling at SahaBee during the last few days. User Information: First name: {user.first_name} Last name: {user.last_name} Personnel code: {user.detail.personnel_code} Username (at SahaBee): {user.username} Sincerely, SahaBee ----------------------- Let the good times roll! https://sahabee.ir ''' message = EmailMessage( 'SahaBee User Timesheet', body_text, from_email=user.email, to=[receiver_email], cc=cc_list, attachments=[( f'timesheet-{user.detail.personnel_code}.xlsx', ExcelConverter.generate_excel_file(user, j_now.year, j_now.month).getvalue(), 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' )]) message.send() logging.info( f"Successfully emailed timesheet of '{user.username}' to '{settings.TIMESHEETS_RECEIVER_EMAIL}'." )
def test_base(self): self.assertEqual( JalaliDateTime(1369, 7, 1, 14, 14, 1, 9111), JalaliDateTime(JalaliDateTime(1369, 7, 1, 14, 14, 1, 9111)), ) g = JalaliDateTime.now() self.assertEqual(g.time(), _time(g.hour, g.minute, g.second, g.microsecond)) g = g.replace(tzinfo=pytz.timezone("America/Los_Angeles")) self.assertEqual( g.timetz(), _time( g.hour, g.minute, g.second, g.microsecond, pytz.timezone("America/Los_Angeles"), ), ) self.assertEqual( JalaliDateTime.fromtimestamp(578723400, pytz.utc), JalaliDateTime(1367, 2, 14, 4, 30, 0, 0, pytz.utc), ) self.assertEqual( JalaliDateTime.utcfromtimestamp(578723400), JalaliDateTime(1367, 2, 14, 4, 30, 0, 0), ) with pytest.raises(TypeError): JalaliDateTime._check_time_fields("20", 1, 61, 1000) with pytest.raises(ValueError): JalaliDateTime(1367, 2, 14, 25, 0, 0, 0) with pytest.raises(ValueError): JalaliDateTime(1367, 2, 14, 22, 61, 0, 0) with pytest.raises(ValueError): JalaliDateTime(1367, 2, 14, 22, 1, 722, 0) with pytest.raises(ValueError): JalaliDateTime(1367, 2, 14, 22, 1, 0, 1000000)
def create_time_table(period): print("Creating the time table...") print('Progress: 0%\r', end='\r') from_day = 15 to_day = 32 in_time = '0' out_time = '0' day_off = 0 months = period prog = 0 year = int(JalaliDateTime.now().strftime('%Y')) for month in months: if month == 0: year = year - 1 while from_day <= to_day: try: day = JalaliDate(year, month, from_day) day_type = day.strftime('%A') day_month = day.strftime("%m") day_date = day.strftime('%d') prog = prog + 1 from_day = from_day + 1 print(f"\rProgress: {round(100*(prog/31))}%", end='\r') if day_type != "Panjshanbeh" and day_type != "Jomeh": date = day.strftime('%Y-%m-%d') day_off = is_off(date) else: day_off = 1 db.execute( "INSERT INTO days VALUES ('{}', '{}', '{}', '{}', '{}', '{}')" .format(day_date, day_month, day_type, in_time, out_time, day_off)) except: from_day = 1 to_day = 15 break print(f"Time table created........") connection.commit()
def _send_user_timesheet(user): j_now = JalaliDateTime.now() if not user.detail.work_email: logging.info(f"User ({user.username}) work email not found. Emailing the corresponding timesheet ignored.") return receiver_email = user.detail.work_email if j_now.day == 1: # The timesheet of the previous month should be sent in the first day of each month. report_jdatetime = j_now - timedelta(days=1) else: report_jdatetime = j_now timesheet_file = ExcelConverter.generate_excel_file(user, report_jdatetime.year, report_jdatetime.month).getvalue() body_text = f'''Hello, Here is the timesheet of you at SahaBee. As soon as possible, forward this email to the Office This email is sent automatically, since you have actively roll-calling at SahaBee during the last few days. User Information: First name: {user.first_name} Last name: {user.last_name} Personnel code: {user.detail.personnel_code} Username (at SahaBee): {user.username} Sincerely, SahaBee ----------------------- Let the good times roll! https://sahabee.ir ''' message = EmailMessage('SahaBee User Timesheet', body_text, to=[receiver_email], attachments=[(f'timesheet-{user.detail.personnel_code}.xlsx', timesheet_file, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')]) message.send() logging.info(f"Successfully emailed timesheet of '{user.username}' to '{settings.TIMESHEETS_RECEIVER_EMAIL}'.")
from datetime import timedelta from persiantools.jdatetime import JalaliDateTime, JalaliDate import pytz import time one_hour_in_ms = 60 * 60 * 1000 one_day_in_ms = one_hour_in_ms * 24 get_current_epoch = lambda : int(round(time.time() * 1000)) get_tehran_tzinfo_by_epoch = lambda e: JalaliDateTime.fromtimestamp(e//1000, pytz.timezone("Asia/Tehran")).tzinfo # will be used indirectly and by other functions now = JalaliDateTime.now(tz=get_tehran_tzinfo_by_epoch(get_current_epoch())) jalali_to_gregorian = lambda j: j.to_gregorian().date() # needed when using plotly epoch_to_jalali = lambda e: JalaliDateTime.fromtimestamp(e/1000, tz=get_tehran_tzinfo_by_epoch(e)) def utc_date_to_jalali(year, month, day): return JalaliDate.to_jalali(year, month, day) def jalali_to_epoch(year, month, day=1, hour=0, minute=0, second=0, milliseconds=0): tehran_tzinfo = get_tehran_tzinfo_by_epoch(int(JalaliDateTime(year, month, day, hour, minute, second, milliseconds*1000).timestamp() * 1000)) return int(JalaliDateTime(year, month, day, hour, minute, second, milliseconds*1000, tzinfo=tehran_tzinfo).timestamp() * 1000) today_epoch = jalali_to_epoch(now.year, now.month, now.day) # --------------------------------------------------------- def back_days_epoch(n): d = now - timedelta(days = n) e = jalali_to_epoch(d.year, d.month, d.day) x = epoch_to_jalali(e) if x.hour == 23: e += one_hour_in_ms
def submit_missings(driver): try: db.execute("CREATE TABLE missings (date TEXT, type TEXT, time TEXT)") except: print('flushing tables') db.execute("DROP TABLE missings") db.execute("CREATE TABLE missings (date TEXT, type TEXT, time TEXT)") today = JalaliDateTime.now().strftime('%m-%d') today = time.strptime(today, '%m-%d') year = JalaliDateTime.now().strftime('%Y') a = '0' b = '0' c = 0 missings = db.execute( 'SELECT day, month FROM days WHERE in_time = ? AND off = ?', (a, c)).fetchall() for missing in missings: m_d = str(missing[0]).zfill(2) m_m = str(missing[1]).zfill(2) day_s = f'{m_m}-{m_d}' day = time.strptime(day_s, '%m-%d') if today < day: break else: pass print(f"input ENTER time for {day_s}:") user_time = input() type = 'enter' date = f'{year}{m_m}{m_d}' db.execute("INSERT INTO missings VALUES ('{}', '{}', '{}')".format( date, type, user_time)) connection.commit() missings = db.execute( 'SELECT day, month FROM days WHERE out_time = ? AND off = ?', (b, c)).fetchall() print("-------------------------------") for missing in missings: m_d = str(missing[0]).zfill(2) m_m = str(missing[1]).zfill(2) day_s = f'{m_m}-{m_d}' day = time.strptime(day_s, '%m-%d') if today < day: break else: pass print(f"input EXIT time for {day_s}:") user_time = input() type = 'exit' date = f'{year}{m_m}{m_d}' db.execute("INSERT INTO missings VALUES ('{}', '{}', '{}')".format( date, type, user_time)) connection.commit() missings = db.execute('SELECT date, type, time FROM missings').fetchall() for missing in missings: submit_time(driver=driver, date=missing[0], time=missing[2], type=missing[1])
def show_message(stdscr, msg): # start thread thread = Thread(target=refresh, args=stdscr) thread.start() thread.join() # Clear and refresh the screen for a blank canvas stdscr.clear() stdscr.refresh() # Start colors in curses curses.start_color() curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_WHITE) # Initialization stdscr.clear() height, width = stdscr.getmaxyx() # Declaration of strings title = JalaliDateTime.now().strftime("%A %d %B %Y %H:%M")[:width - 1] message = msg[:width - 1] statusbarstr = "Modern University |" # Centering calculations start_x_title = int((width // 2) - (len(title) // 2) - len(title) % 2) start_y = int((height // 2) - 2) # Render status bar stdscr.attron(curses.color_pair(3)) try: stdscr.addstr(height - 1, 0, statusbarstr) stdscr.addstr(height - 1, len(statusbarstr), " " * (width - len(statusbarstr) - 1)) except curses.error: pass stdscr.attroff(curses.color_pair(3)) # Turning on attributes for title stdscr.attron(curses.color_pair(2)) stdscr.attron(curses.A_BOLD) # Rendering title try: stdscr.addstr(start_y, start_x_title, title) except curses.error: pass # Turning off attributes for title stdscr.attroff(curses.color_pair(2)) stdscr.attroff(curses.A_BOLD) stdscr.attron(curses.color_pair(2)) # Print rest of text stdscr.addstr(start_y + 1, 0, message) stdscr.attroff(curses.color_pair(2)) # Refresh the screen stdscr.refresh() sleep(2)
#======================= change log ============================ # version 1.0 #======================= configs ================================ fileName = 'conf.txt' with open(os.path.join(sys.path[0], fileName), 'r') as f: data = f.read().splitlines() try: username = data[0] password = data[1] except: print( "Please put your username and password in the conf.txt file.\nUsername must be in the first line and the password must be in the second line.\nExiting now..." ) exit() time_now = JalaliDateTime.now().strftime('%H:%M') date_now = JalaliDateTime.now().strftime('%Y/%m/%d') connection = sqlite3.connect("pts.db") db = connection.cursor() try: db.execute( "CREATE TABLE days (day INTEGER, month INTEGER, day_type TEXT, in_time TEXT, out_time TEXT, off INTEGER)" ) except: print('flushing tables') db.execute("DROP TABLE days") db.execute( "CREATE TABLE days (day INTEGER, month INTEGER, day_type TEXT, in_time TEXT, out_time TEXT, off INTEGER)" )
def draw_menu(stdscr, table, message='----', alter='', status='Enter b to back |'): # start thread thread = Thread(target=refresh, args=stdscr) thread.start() thread.join() # Clear and refresh the screen for a blank canvas stdscr.clear() stdscr.refresh() # Start colors in curses curses.start_color() curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_WHITE) curses.init_pair(4, curses.COLOR_BLUE, curses.COLOR_BLACK) # Initialization stdscr.clear() height, width = stdscr.getmaxyx() # Declaration of strings title = JalaliDateTime.now().strftime("%A %d %B %Y %H:%M") statusbarstr = "Modern University | {}".format(status) # Centering calculations start_x_title = int((width // 2) - (len(title) // 2) - len(title) % 2) start_x_keystr = int((width // 2) - (len(alter) // 2) - len(alter) % 2) start_y = int((height // 2) - 2) # Render status bar stdscr.attron(curses.color_pair(3)) try: stdscr.addstr(height - 1, 0, statusbarstr) stdscr.addstr(height - 1, len(statusbarstr), " " * (width - len(statusbarstr) - 1)) except curses.error: pass stdscr.attroff(curses.color_pair(3)) # Turning on attributes for title stdscr.attron(curses.color_pair(2)) stdscr.attron(curses.A_BOLD) # Rendering title try: stdscr.addstr(start_y, start_x_title, title) except curses.error: pass # Turning off attributes for title stdscr.attroff(curses.color_pair(2)) stdscr.attroff(curses.A_BOLD) # Print rest of text stdscr.attron(curses.color_pair(4)) try: stdscr.addstr(int(start_y / 2) + 1, 0, table) stdscr.attroff(curses.color_pair(4)) stdscr.addstr(int(start_y / 2) + 1, (width // 2) - 2, message) stdscr.addstr(int(start_y / 2) + 2, start_x_keystr, alter) except curses.error: pass stdscr.attroff(curses.color_pair(4)) # Refresh the screen stdscr.refresh() # Wait for next input k = stdscr.getch() return k
def show_time_call(cli: Client, msg: Message): print("show_time_call") today = JalaliDateTime.now(pytz.timezone("Asia/Tehran")); msg.reply_text(today.strftime("%c" + "\n\nTime zone: **Asia/Tehran**"))
from persiantools.jdatetime import JalaliDateTime, JalaliDate import pytz today = JalaliDateTime.now(pytz.timezone("Asia/Tehran")) print(today.strftime("%c")) import re p = re.compile(r'^(/)?date$|^(/)?time$|^تاریخ$', re.IGNORECASE) m = re.search(p, '/تاریخ') print(m)
def export(request): data = {} #operators can not know each other leads if request.user.is_superuser: leads = Lead.objects.order_by('-id') if "operator" in request.GET and len(request.GET["operator"])>0: data.update( { "operator":int(request.GET["operator"]) } ) operator = request.GET["operator"] if operator: leads = leads.filter(operator__id=operator) else: leads = Lead.objects.filter(operator__id=request.user.id).order_by('-id') #search if "phrase" in request.GET and len(request.GET["phrase"])>0: data.update( { "phrase":request.GET["phrase"] } ) phrase = request.GET["phrase"] if phrase: p_name = leads.filter(name_and_family__icontains=phrase) p_phone = leads.filter(phone_number__icontains=phrase) p_comment = leads.filter(comments__text__icontains=phrase) p_question = leads.filter(question__icontains=phrase) leads = p_name | p_phone | p_comment | p_question leads = leads.distinct() if "origin" in request.GET and len(request.GET["origin"])>0: data.update( { "origin":int(request.GET["origin"]) } ) origin = request.GET["origin"] if origin: leads = leads.filter(origin__id=origin) if "gender" in request.GET and len(request.GET["gender"])>0: data.update( { "gender":request.GET["gender"] } ) gender = request.GET["gender"] if gender: leads = leads.filter(gender=gender) if "status" in request.GET and len(request.GET["status"])>0: data.update( { "status":request.GET["status"] } ) status = request.GET["status"] if status: leads = leads.filter(register_status=status) if "label1" in request.GET and len(request.GET["label1"])>0: data.update( { "label1":request.GET["label1"] } ) label1 = request.GET["label1"] if label1: leads = leads.filter(label__label__color_code=label1) if "label2" in request.GET and len(request.GET["label2"])>0: data.update( { "label2":request.GET["label2"] } ) label2 = request.GET["label2"] if label2: leads = leads.filter(label__label__color_code=label2) if "date_from" in request.GET and len(request.GET["date_from"])>0: date_from = request.GET["date_from"] if date_from: date_from_s =date_from.split("/") date_from = JalaliDate(int(date_from_s[0]), int(date_from_s[1]), int(date_from_s[2])).to_gregorian() data.update( { "date_from":date_from.strftime("%Y-%m-%d")} ) leads = leads.filter(led_time__gte=date_from) if "date_to" in request.GET and len(request.GET["date_to"])>0: date_to = request.GET["date_to"] if date_to: date_to_s =date_to.split("/") date_to = JalaliDate(int(date_to_s[0]), int(date_to_s[1]), int(date_to_s[2])).to_gregorian() data.update( { "date_to":date_to.strftime("%Y-%m-%d")} ) date_to += timedelta(days=1) leads = leads.filter(led_time__lte=date_to) # if there is no date show last month if "date_from" not in data: date = datetime.now() date -= timedelta(days=30) leads = leads.filter(led_time__gte=date) date = date.strftime("%Y-%m-%d") data.update( { "date_from":date} ) if "date_to" not in data: date = datetime.now() date += timedelta(days=1) leads = leads.filter(led_time__lte=date) date = date.strftime("%Y-%m-%d") date = data.update( { "date_to":date} ) #leads paginator paginator = Paginator(leads, 30) page = request.GET.get('page') if page: paged_leads = paginator.page(page) else: paged_leads = paginator.page(1) #page = paginator.get_page(page) comments = Comment.objects.all() labels = Label.objects.all() labels_def = LabelDefinition.objects.all() origins = Origin.objects.all() time = JalaliDateTime.now().strftime("%H:%M %Y-%m-%d") data.update( {'comments': comments, 'leads':paged_leads, 'labels': labels, 'time': time, 'labels_def': labels_def, \ origins:'origins','REGISTRATION_STATUS':REGISTRATION_STATUS, 'GENDER_CHOICES':GENDER_CHOICES,\ 'ORIGIN_DESCRIPTION':ORIGIN_DESCRIPTION, 'USER_NAME_AND_FAMILY':USER_NAME_AND_FAMILY,\ 'LABELDEFINITION_TAG':LABELDEFINITION_TAG,} ) return render(request,'leads/export/export.html', data)