def test_hash(self): j1 = JalaliDate.today() j2 = JalaliDate(1367, 2, 14) j3 = JalaliDate(date(1988, 5, 4)) self.assertEqual({j1: "today", j2: "majid1", j3: "majid2"}, {JalaliDate.today(): "today", JalaliDate(1367, 2, 14): "majid2"})
def test_gregorian_to_shamsi(self): self.assertEqual(JalaliDate(date(1988, 5, 4)), JalaliDate(1367, 2, 14)) self.assertEqual(JalaliDate(date(2122, 1, 31)), JalaliDate(1500, 11, 11)) self.assertEqual(JalaliDate(date(2017, 3, 20)), JalaliDate(1395, 12, 30)) self.assertEqual(JalaliDate(date(2000, 1, 1)), JalaliDate(1378, 10, 11)) self.assertEqual(JalaliDate(date(2017, 10, 19)), JalaliDate(1396, 7, 27)) self.assertEqual(JalaliDate(date(2019, 2, 18)), JalaliDate(1397, 11, 29)) self.assertEqual(JalaliDate(date.today()), JalaliDate.today()) self.assertEqual(JalaliDate.to_jalali(1990, 9, 23), JalaliDate(1369, 7, 1)) self.assertEqual(JalaliDate.to_jalali(1990, 9, 23), JalaliDate(1369, 7, 1)) self.assertEqual(JalaliDate.to_jalali(2013, 9, 16), JalaliDate(1392, 6, 25)) self.assertEqual(JalaliDate.to_jalali(2018, 3, 20), JalaliDate(1396, 12, 29))
def test_shamsi_to_gregorian(self): self.assertEqual(JalaliDate(1367, 2, 14).to_gregorian(), date(1988, 5, 4)) self.assertEqual(JalaliDate(1369, 7, 1).to_gregorian(), date(1990, 9, 23)) self.assertEqual(JalaliDate(1395, 3, 21).to_gregorian(), date(2016, 6, 10)) self.assertEqual(JalaliDate(1395, 12, 9).to_gregorian(), date(2017, 2, 27)) self.assertEqual(JalaliDate(1395, 12, 30).to_gregorian(), date(2017, 3, 20)) self.assertEqual(JalaliDate(1396, 1, 1).to_gregorian(), date(2017, 3, 21)) self.assertEqual(JalaliDate(1400, 6, 31).to_gregorian(), date(2021, 9, 22)) self.assertEqual(JalaliDate(1396, 7, 27).to_gregorian(), date(2017, 10, 19)) self.assertEqual(JalaliDate(1397, 11, 29).to_gregorian(), date(2019, 2, 18)) self.assertEqual(JalaliDate.today().to_gregorian(), date.today())
def test_additions(self): self.assertEqual(JalaliDate(JalaliDate(1395, 3, 21)), JalaliDate(1395, 3, 21)) self.assertEqual(JalaliDate.days_before_month(1), 0) self.assertEqual(JalaliDate.days_before_month(12), 336) self.assertEqual(JalaliDate(1395, 1, 1).replace(1367), JalaliDate(1367, 1, 1)) self.assertEqual(JalaliDate(1395, 1, 1).replace(month=2), JalaliDate(1395, 2, 1)) self.assertEqual(JalaliDate(1367, 1, 1).replace(year=1396, month=7), JalaliDate(1396, 7, 1)) self.assertEqual(JalaliDate(1395, 1, 1, "en").replace(1367, 2, 14, "fa"), JalaliDate(1367, 2, 14, "en")) self.assertEqual(JalaliDate.fromtimestamp(time()), JalaliDate.today()) self.assertEqual(JalaliDate.fromtimestamp(578707200), JalaliDate(1367, 2, 14)) self.assertEqual(JalaliDate.fromtimestamp(1508371200), JalaliDate(1396, 7, 27)) try: JalaliDate(1400, 1, 1, "us") except ValueError: assert True else: assert False
def test_chackdate(self): self.assertEqual(JalaliDate.chack_date(1367, 2, 14), True) self.assertEqual(JalaliDate.chack_date(1395, 12, 30), True) self.assertEqual(JalaliDate.chack_date(1394, 12, 30), False) self.assertEqual(JalaliDate.chack_date(13, 13, 30), False) self.assertEqual(JalaliDate.chack_date(0, 0, 0), False) self.assertEqual(JalaliDate.chack_date(9378, 0, 0), False) self.assertEqual(JalaliDate.chack_date("1300", "1", "1"), False) self.assertEqual(JalaliDate.chack_date(1396, 12, 30), False) self.assertEqual(JalaliDate.chack_date(1397, 7, 1), True) self.assertEqual(JalaliDate.chack_date(1396, 7, 27), True) self.assertEqual(JalaliDate.chack_date(1397, 11, 29), True)
def test_isocalendar(self): self.assertEqual(JalaliDate(1364, 1, 31).isocalendar(), (1364, 6, 1)) self.assertEqual(JalaliDate(1398, 3, 17).isocalendar(), (1398, 12, 7)) self.assertEqual(JalaliDate(1398, 1, 1).isocalendar(), (1398, 1, 6)) self.assertEqual(JalaliDate(1399, 1, 2).isocalendar(), (1399, 2, 1))
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)
def __init__(self, user, rollouts, starting_date): self.rollouts = rollouts self.user = user self.starting_date = starting_date self.starting_date_jalali = JalaliDate(starting_date)
from persiantools.jdatetime import JalaliDate # pip install persiantools from datetime import timedelta import time, datetime now = datetime.datetime.now() year = (now.strftime("%Y")) day = (now.strftime("%d")) month = (now.strftime("%m")) now_date_string = '{}-{}-{}'.format(year, month, day) print('date_en :', now_date_string) now_year = now.year now_month = now.month now_day = now.day date_fa = JalaliDate(datetime.date(now_year, now_month, now_day)) print('date_fa :', date_fa)
def utc_date_to_jalali(year, month, day): return JalaliDate.to_jalali(year, month, day)
def find_dates(sentence_lem): fa_dates = [] indexes = [] sentence = find_dates_replace(sentence_lem) for regX in [ "امروز", "دیروز", "فردا", "پارسال", "امسال", r"([\u0660-\u0669]|[\d])+[\s]روز[\s]پیش", r"([\u0660-\u0669]|[\d])+[\s]هفته[\s]پیش", r"([\u0660-\u0669]|[\d])+[\s]سال[\s]پیش", r"([\u0660-\u0669]|[\d])+[\s]روز[\s]بعد", r"([\u0660-\u0669]|[\d])+[\s]هفته[\s]بعد", r"([\u0660-\u0669]|[\d])+[\s]سال[\s]بعد" ]: en_datetimes = [x.group() for x in re.finditer(regX, sentence)] # if re.search(regX, sentence) is not None: # en_datetime = dateparser.parse(re.search(regX, sentence).group(0), # settings={'TIMEZONE': '+0330'}) for strDate in en_datetimes: indexes.append(sentence_lem.find(strDate)) en_datetime = dateparser.parse(strDate, settings={'TIMEZONE': '+0330'}) fa_datetime = JalaliDate(en_datetime) fa_dates.append(fa_datetime.strftime('%Y-%m-%d')) # find dates like "18 اسفند" dates = [ x.group() for x in re.finditer(r"\d+[\s][\u0600-\u06FF]+", sentence) ] for i in range(len(dates)): for per_month in [ 'فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور', 'مهر', 'ابان', 'اذر', 'دی', 'بهمن', 'اسفند' ]: if per_month in dates[i]: indexes.append(sentence_lem.find(dates[i])) en_datetime = JalaliCalendar(dates[i]).get_date() fa_datetime = JalaliDate(en_datetime.date_obj) temp = fa_datetime.strftime('%Y-%m-%d') if len(fa_dates) <= i: year = '1399' # TODO - FIX FOR NEXT YEAR :D else: year = fa_dates[i].split("-")[0] month = temp.split("-")[1] day = temp.split("-")[2] if len(fa_dates) <= i: fa_dates.append(f"{year}-{month}-{day}") else: fa_dates[i] = f"{year}-{month}-{day}" if len(fa_dates) == 0: indexes = [0] en_datetime = dateparser.parse('امروز', settings={'TIMEZONE': '+0330'}) fa_datetime = JalaliDate(en_datetime) fa_dates.append(fa_datetime.strftime('%Y-%m-%d')) # find dates like "سال 99", "سال 1399" dates = [ x.group() for x in re.finditer(r"((سال)|(کدام روز))[\s]\d+", sentence) ] for i in range(len(dates)): splited = dates[i].split(" ") year = splited[len(splited) - 1] if len(year) == 2: year = '13' + year year = unidecode(year) month = fa_dates[i].split("-")[1] day = fa_dates[i].split("-")[2] fa_dates[i] = f"{year}-{month}-{day}" fa_dates = [x for _, x in sorted(zip(indexes, fa_dates))] return fa_dates
def jalali_date(self): return JalaliDate(self.birth_date).strftime("%Y/%m/%d")
def answer_per_question(Question, model, tokenizer, all_events, all_event_keys): answer, method = find(Question, model, tokenizer, all_events, all_event_keys) answer_sentence = "" try: answer["type"] = str(predict(Question)) except Exception: raise ValueError("Type Predict Error!") if answer["type"] == '1': # HANDLED BY ARGUMENTS # method = "temp" time_len = len(answer["time"]) if answer["religious_time"]: time_len = 1 time, answer["api_url"] = find_time_from_religious(answer) answer["time"].extend(time) en_datetime = dateparser.parse('امروز', settings={'TIMEZONE': '+0330'}) naive_dt = JalaliDate(en_datetime) d1 = datetime.datetime.strptime(answer['date'][0], "%Y-%m-%d") difference_days = d1.day - naive_dt.day if not answer["time"]: hour = datetime.datetime.now().hour if hour < 12 or difference_days > 0: answer["time"] = ["12:00"] else: if (hour + 1) == 24: hour = 0 time = str( str(hour + 1).zfill(2) + ":" + str(datetime.datetime.now().minute).zfill(2)) answer["time"] = [time] try: if "اختلاف" in Question or "تفاوت" in Question: temps, urls, logic1, logic2 = weather_difference( Question, answer, ' و ') temp = round(abs(temps[1] - temps[0]), 2) answer_mode = 1 elif "سردتر " in Question or "سرد تر " in Question: temps, urls, logic1, logic2 = weather_difference( Question, answer, ' یا ') if temps[1] < temps[0]: answer_number = 1 temp = find_fit_word(answer, True) else: answer_number = 0 temp = find_fit_word(answer, False) answer_mode = 2 elif "گرمتر " in Question or "گرمتر " in Question or "گرم تر " in Question: temps, urls, logic1, logic2 = weather_difference( Question, answer, ' یا ') if temps[1] > temps[0]: answer_number = 1 temp = find_fit_word(answer, True) else: answer_number = 0 temp = find_fit_word(answer, False) answer_mode = 3 else: greg_date = convert_date(answer["date"][0], "shamsi", "greg") + " " + answer["time"][0] temp, cond, url, logic1 = find_weather_from_city_date( Question, answer["city"][0], greg_date) urls = [url] answer_mode = 4 answer["api_url"].extend(urls) if method == "temp": answer["result"] = str(temp) elif method == "cond": answer["result"] = cond if time_len == 0: answer["time"] = [] else: answer["time"] = answer["time"][:time_len] if answer_mode == 0: pass elif answer_mode == 1: answer_sentence = weather_logical_sentence( answer, logic1, logic2, 'اختلاف') elif answer_mode == 2: answer_sentence = weather_logical_sentence( answer, logic1, logic2, 'سردتر', answer_number) elif answer_mode == 3: answer_sentence = weather_logical_sentence( answer, logic1, logic2, 'گرمتر', answer_number) elif answer_mode == 4: answer_sentence = weather_sentence(answer, logic1) if answer["religious_time"]: answer["time"] = [] except Exception: # raise ValueError("Type 1 Error!") pass elif answer["type"] == '2': try: result, answer["api_url"] = find_time_from_religious(answer) answer["result"] = result[0] answer_sentence = religion_sentence(answer) except Exception: # raise ValueError("Type 2 Error!") pass elif answer["type"] == '3': try: t = Time(answer["city"][0]) res = t.send_request() answer["result"] = res answer["api_url"] = [t.url] answer["date"] = [] answer["time"] = [] answer_sentence = time_sentence(answer) except Exception: # raise ValueError("Type 3 Error!") pass elif answer["type"] == '4': answer["city"] = [] try: answer["api_url"] = ["https://www.time.ir/"] if 'مناسبت' in Question: answer["result"] = answer["event"][0] answer["event"] = [] else: if answer["calendar_type"] and answer["date"]: target = answer["calendar_type"][0] if target == "شمسی": answer["result"] = convert_date( answer["date"][0], "shamsi", "shamsi") elif target == "قمری" or target == "هجری": answer["result"] = convert_date( answer["date"][0], "shamsi", "hijri") elif target == "میلادی": answer["result"] = convert_date( answer["date"][0], "shamsi", "greg") elif answer["date"]: answer["result"] = answer["date"][0] answer_sentence = date_sentence(answer) except Exception: # raise ValueError("Type 4 Error!") pass elif answer["type"] == '-1': answer = { 'type': '-1', 'city': [], 'date': [], 'time': [], 'religious_time': [], 'calendar_type': [], 'event': [], 'api_url': [], 'result': '' } answer_sentence = unknown_sentence() return answer, answer_sentence
def test_leap(self): self.assertEqual(JalaliDate.is_leap(1358), True) self.assertEqual(JalaliDate.is_leap(1366), True) self.assertEqual(JalaliDate.is_leap(1367), False) self.assertEqual(JalaliDate.is_leap(1370), True) self.assertEqual(JalaliDate.is_leap(1387), True) self.assertEqual(JalaliDate.is_leap(1395), True) self.assertEqual(JalaliDate.is_leap(1396), False) self.assertEqual(JalaliDate.is_leap(1397), False) self.assertEqual(JalaliDate.is_leap(1398), False) self.assertEqual(JalaliDate.is_leap(1399), True) self.assertEqual(JalaliDate.is_leap(1400), False) self.assertEqual(JalaliDate.is_leap(1403), True)
def from_gregorian_date(self,greg_date): return JalaliDate.to_jalali(greg_date).strftime("%Y/%m/%d")
def test_format(self): j = JalaliDate(date(1988, 5, 4)) self.assertEqual(j.isoformat(), "1367-02-14") self.assertEqual(j.strftime("%a %A %w"), "Cha Chaharshanbeh 4") j.locale = "fa" self.assertEqual(j.isoformat(), "۱۳۶۷-۰۲-۱۴") self.assertEqual(j.strftime("%a %A %w"), "چ چهارشنبه ۴") j = JalaliDate(1395, 3, 1) self.assertEqual(j.strftime("%d %b %B"), "01 Kho Khordad") self.assertEqual(j.strftime("%m %m %y %Y"), "03 03 95 1395") self.assertEqual(j.strftime("%p %j %j %U %W %%"), "AM 063 063 10 10 %") self.assertEqual(j.strftime("%c"), j.ctime()) self.assertEqual(j.strftime("%c"), "Shanbeh 01 Khordad 1395") self.assertEqual(j.strftime("%x"), "95/03/01") self.assertEqual(format(j, "%c"), j.ctime()) self.assertEqual(format(j), "1395-03-01") self.assertEqual(j.__repr__(), "JalaliDate(1395, 3, 1, Shanbeh)") j.locale = "fa" self.assertEqual(j.strftime("%d %b %B"), "۰۱ خرد خرداد") self.assertEqual(j.strftime("%m %m %y %Y"), "۰۳ ۰۳ ۹۵ ۱۳۹۵") self.assertEqual(j.strftime("%p %j %j %U %W %%"), "ق.ظ ۰۶۳ ۰۶۳ ۱۰ ۱۰ %") self.assertEqual(j.strftime("%c"), j.ctime()) self.assertEqual(j.strftime("%c"), "شنبه ۰۱ خرداد ۱۳۹۵") self.assertEqual(j.strftime("%x"), "۹۵/۰۳/۰۱") self.assertEqual(format(j, "%c"), j.ctime()) self.assertEqual(j.__repr__(), "JalaliDate(1395, 3, 1, Shanbeh)") self.assertEqual(format(j), "۱۳۹۵-۰۳-۰۱") j = JalaliDate(1397, 11, 29) self.assertEqual(j.strftime("%c"), "Doshanbeh 29 Bahman 1397") self.assertEqual(format(j), "1397-11-29") j.locale = "fa" self.assertEqual(j.strftime("%c"), "دوشنبه ۲۹ بهمن ۱۳۹۷") self.assertEqual(format(j), "۱۳۹۷-۱۱-۲۹")
def test(): dd = request Product_Id = request.form.get('Product_Id') Product_Id_split = Product_Id.split(",") new_Product_Id_split = [] print('a') # exit(0) for e in Product_Id_split: for sub_e in e.split(","): new_Product_Id_split.append(int(sub_e)) Daily_off_DateTime = request.form.get('Daily_off_DateTime') if Daily_off_DateTime == '': Daily_off_DateTime = datetime.min else: Date = Daily_off_DateTime[:-9] Time = Daily_off_DateTime[10:] Time = digits.fa_to_en(Time) Date_split = Date.split("-") Daily_off_DateTime = JalaliDate(int(Date_split[0]), int(Date_split[1]), int(Date_split[2])).to_gregorian() Daily_off_DateTime = str(Daily_off_DateTime) + Time Daily_Off_Category = request.form.get('Daily-Off_Category') Owner_Id = request.form.get('Owner_Id') # return (str(select)) # just to see what select is #segment = """ #insert into bi.dailyoff_products (producer_id , created_at ) values (""" + Product_Id + """ #, """ + Daily_off_DateTime + """ ) """ new_Product_Id_split = tuple(new_Product_Id_split) #params = {'new_Product_Id_split': new_Product_Id_split} Products = get_Product(new_Product_Id_split, Daily_off_DateTime) if Products == []: Products.append(0) connect = None cur = None for p_id in Product_Id_split: connect = get_connection() cur = connect.cursor() if int(p_id) not in Products: #continue try: segment = """ INSERT INTO bi.dailyoff_products (product_id , created_at ,type ,tag) values (%s,%s,%s,%s)""" record_to_insert = (int(p_id), Daily_off_DateTime , Daily_Off_Category , Owner_Id) cur.execute(segment, record_to_insert) connect.commit() count = cur.rowcount print(count, "Record inserted successfully into dailyoff_products table") #ps_cursor.executemany() # ps_cursor.execute(segment) # records = ps_cursor.fetchall() except (Exception, psycopg2.Error) as error: if connect: print("Failed to insert record into mobile table", error) #finally: # closing database connection. if connect: cur.close() print("PostgreSQL connection is closed") return 'done!'