예제 #1
0
 def to_python(self, value):
     """
     Validates that the input can be converted to a datetime. Returns a
     Python datetime.datetime object.
     """
     if value in validators.EMPTY_VALUES:
         return None
     if isinstance(value, jdatetime.datetime):
         return value
     if isinstance(value, jdatetime.date):
         return jdatetime.datetime(value.year, value.month, value.day)
     if isinstance(value, list):
         # Input comes from a SplitDateTimeWidget, for example. So, it's two
         # components: date and time.
         if len(value) != 2:
             raise ValidationError(self.error_messages["invalid"])
         if value[0] in validators.EMPTY_VALUES and value[1] in validators.EMPTY_VALUES:
             return None
         value = "%s %s" % tuple(value)
     for format in self.input_formats or formats.get_format("DATETIME_INPUT_FORMATS"):
         try:
             return jdatetime.datetime(*time.strptime(value, format)[:6])
         except ValueError:
             continue
     raise ValidationError(self.error_messages["invalid"])
예제 #2
0
    def test_strftime(self):
        s = jdatetime.date(1390, 2, 23)
        string_format = "%a %A %b %B %c %d %H %I %j %m %M %p %S %w %W %x %X %y %Y %f %z %Z"
        output = 'Jom Jomeh Ord Ordibehesht Jom Ord 23 00:00:00 1390 23 00 00 054 02 00 AM 00 6 7 02/23/90 00:00:00 90 1390 000000  '
        self.assertEqual(s.strftime(string_format), output)

        dt = jdatetime.datetime(1390, 2, 23, 12, 13, 14, 1)
        string_format = "%a %A %b %B %c %d %H %I %j %m %M %p %S %w %W %x %X %y %Y %f"
        output = 'Jom Jomeh Ord Ordibehesht Jom Ord 23 12:13:14 1390 23 12 12 054 02 13 AM 14 6 7 02/23/90 12:12:14 90 1390 000001'
        self.assertEqual(dt.strftime(string_format), output)

        class NYCTime(jdatetime.tzinfo):
            def utcoffset(self, dt):
                return jdatetime.timedelta(hours=-4)

            def tzname(self, dt):
                return "EDT"

            def dst(self, dt):
                return jdatetime.timedelta(0)

        nyc = NYCTime()
        dt = jdatetime.datetime(1389, 2, 17, 19, 10, 2, tzinfo=nyc)
        self.assertEqual(True, dt.strftime("%Z %z") == "EDT -0400")

        teh = TehranTime()
        dt = jdatetime.datetime(1389, 2, 17, 19, 10, 2, tzinfo=teh)
        self.assertEqual(True, dt.strftime("%Z %z") == "IRDT +0330")
예제 #3
0
    def test_datetime_calculation_on_two_dates(self):
        date_1394 = jdatetime.datetime(1394,1,1)
        date_1395 = jdatetime.datetime(1395,1,1)

        day_diff = date_1395 - date_1394

        self.assertEqual(day_diff, datetime.timedelta(365))

        day_diff = date_1394 - date_1395

        self.assertEqual(day_diff, datetime.timedelta(-365))
예제 #4
0
    def test_datetime_calculation_on_timedelta(self):
        date_1395 = jdatetime.datetime(1395,1,1)
        day_before = date_1395 - jdatetime.timedelta(days=1)
        day_after = date_1395 + jdatetime.timedelta(days=1)

        self.assertEqual(day_before, jdatetime.datetime(1394, 12, 29, 0, 0))
        self.assertEqual(day_after, jdatetime.datetime(1395, 1, 2, 0, 0))

        day_after = jdatetime.timedelta(days=1) + date_1395

        self.assertEqual(day_before, jdatetime.datetime(1394, 12, 29, 0, 0))
        self.assertEqual(day_after, jdatetime.datetime(1395, 1, 2, 0, 0))
예제 #5
0
    def test_datetime_eq_diff_tz(self):
        gmt = GMTTime()
        teh = TehranTime()

        dt_gmt = datetime.datetime(2015, 6, 27, 0, 0, 0, tzinfo=gmt)
        dt_teh = datetime.datetime(2015, 6, 27, 3, 30, 0, tzinfo=teh)
        self.assertEqual(True, dt_teh == dt_gmt, "In standrd python datetime, __eq__ considers timezone")

        jdt_gmt = jdatetime.datetime(1389, 2, 17, 0, 0, 0, tzinfo=gmt)

        jdt_teh = jdatetime.datetime(1389, 2, 17, 3, 30, 0, tzinfo=teh)

        self.assertEqual(True, jdt_teh == jdt_gmt)
예제 #6
0
 def filter(self, *args, **kwargs):
     """if filter is year we divide to __gte and __lte"""
     new_kwargs = {}
     for k in kwargs:
         if "__year" in k:
             filed_name = k.split("__year")
             first_year = jdatetime.datetime(int(kwargs[k]), 1, 1)
             new_kwargs["%s__gte" % filed_name[0]] = jdatetime.datetime(int(kwargs[k]), 1, 1)
             last_day = 29
             if first_year.isleap():
                 last_day = 30
             new_kwargs["%s__lte" % filed_name[0]] = jdatetime.datetime(int(kwargs[k]), 12, last_day, 23, 59, 59)
         else:
             new_kwargs[k] = kwargs[k]
     return models.Manager.filter(self, *args, **new_kwargs)
예제 #7
0
 def test_subtract_timedelta_keeps_source_datetime_locale(self):
     jdate = jdatetime.datetime(1397, 4, 23, locale='nl_NL')
     new_jdate = jdate - datetime.timedelta(days=1)
     self.assertEqual(new_jdate.year, 1397)
     self.assertEqual(new_jdate.month, 4)
     self.assertEqual(new_jdate.day, 22)
     self.assertEqual(new_jdate.locale, 'nl_NL')
예제 #8
0
    def test_strptime_handles_alphabets_in_format(self):
        date_string = "1363-6-6T12:13:14"
        date_format = "%Y-%m-%dT%H:%M:%S"
        dt1 = jdatetime.datetime.strptime(date_string, date_format)
        dt2 = jdatetime.datetime(1363, 6, 6, 12, 13, 14)

        self.assertEqual(dt1, dt2)
예제 #9
0
 def test_replace_keeps_date_locale(self):
     dt = jdatetime.datetime(1397, 4, 24, locale='nl_NL')
     args = {'year': 1390,
             'month': 12,
             'hour': 13,
             }
     self.assertEqual(dt.replace(**args).locale, 'nl_NL')
예제 #10
0
    def test_replace(self):
        dt = jdatetime.datetime.today()
        args = {"year": 1390, "month": 12, "day": 1, "hour": 13, "minute": 14, "second": 15, "microsecond": 1233}
        dtr = dt.replace(**args)
        dtn = jdatetime.datetime(1390, 12, 1, 13, 14, 15, 1233)

        self.assertEqual(True, dtr == dtn)
예제 #11
0
    def test_strptime(self):
        date_string = "1363-6-6 12:13:14"
        date_format = "%Y-%m-%d %H:%M:%S"
        dt1 = jdatetime.datetime.strptime(date_string, date_format)
        dt2 = jdatetime.datetime(1363, 6, 6, 12, 13, 14)

        self.assertEqual(True, dt1 == dt2)
예제 #12
0
    def to_python(self, value):
        """
        Validates that the input can be converted to a datetime. Returns a
        Python datetime.datetime object.
        """
        if value in validators.EMPTY_VALUES:
            return None
        if isinstance(value, jdatetime.datetime):
            return from_current_timezone(value)
        if isinstance(value, jdatetime.date):
            result = jdatetime.datetime(value.year, value.month, value.day)
            return from_current_timezone(result)
        if isinstance(value, list):
            # Input comes from a SplitDateTimeWidget, for example. So, it's two
            # components: date and time.
            if len(value) != 2:
                raise exceptions.ValidationError(self.error_messages['invalid'])
            if value[0] in validators.EMPTY_VALUES and value[1] in validators.EMPTY_VALUES:
                return None
            value = '%s %s' % tuple(value)

        groups = re.search(
            r'(?P<year>[\d]{1,4})-(?P<month>[\d]{1,2})-(?P<day>[\d]{1,2}) '
            r'(?P<hour>[\d]{1,2}):(?P<minute>[\d]{1,2})'
            r'(:(?P<second>[\d]{1,2}))?(.(?P<microsecond>[\d]{1,5}))?',
            value
        )
        try:
            microsecond = int(groups.group('microsecond') or 0)
            second = int(groups.group('second') or 0)
            result = jdatetime.datetime(year=int(groups.group('year')),
                                      month=int(groups.group('month')),
                                      day=int(groups.group('day')),
                                      hour=int(groups.group('hour')),
                                      minute=int(groups.group('minute')),
                                      second=second,
                                      microsecond=microsecond)
            return from_current_timezone(result)

        except (ValueError, AttributeError):
            pass

        raise exceptions.ValidationError(self.error_messages['invalid'])
예제 #13
0
 def test_with_pytz(self):
     try:
         import pytz
         from pytz import timezone
     except:
         pytz = None
     if pytz:
         tehran = timezone('Asia/Tehran')
         date = jdatetime.datetime(1394, 1, 1, 0, 0, 0, tzinfo=tehran)
         self.assertEqual(str(date), "1394-01-01 00:00:00+0326")
예제 #14
0
 def test_as_locale_returns_same_datetime_with_specified_locale(self):
     jdt_en = jdatetime.datetime(1397, 4, 23, 11, 47, 30, 40, locale='en_US')
     jdt_fa = jdt_en.aslocale('fa_IR')
     self.assertEqual(jdt_fa.year, 1397)
     self.assertEqual(jdt_fa.month, 4)
     self.assertEqual(jdt_fa.day, 23)
     self.assertEqual(jdt_fa.hour, 11)
     self.assertEqual(jdt_fa.minute, 47)
     self.assertEqual(jdt_fa.second, 30)
     self.assertEqual(jdt_fa.microsecond, 40)
     self.assertEqual(jdt_fa.locale, 'fa_IR')
예제 #15
0
파일: test.py 프로젝트: knv/python-jalali
    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)
        self.assertEqual(True, today != (jdatetime.date( today.year, today.month, today.day ) + jdatetime.timedelta(days=1) ) )

        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 == None)
예제 #16
0
    def to_python(self, value):
        if value is None:
            return value

        if isinstance(value, jdatetime.datetime):
            return value
        if isinstance(value, jdatetime.date):
            try:
                return jdatetime.datetime(value.year, value.month, value.day)
            except ValueError:
                raise exceptions.ValidationError(
                    self.error_messages['invalid'])
        return self.parse_date(value)
예제 #17
0
    def test_replace(self):
        dt = jdatetime.datetime.today()
        args = {'year': 1390,
                'month': 12,
                'day': 1,
                'hour': 13,
                'minute': 14,
                'second': 15,
                'microsecond': 1233
                }
        dtr = dt.replace(**args)
        dtn = jdatetime.datetime(1390, 12, 1, 13, 14, 15, 1233)

        self.assertEqual(True, dtr == dtn)
예제 #18
0
    def test_datetime_raise_exception_on_invalid_calculation(self):
        date_1395 = jdatetime.datetime(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
예제 #19
0
    def test_strftime_in_fa_locale(self):
        s = jdatetime.date(1390, 2, 23, locale='fa_IR')
        string_format = "%a %A %b %B %c %d %H %I %j %m %M %p %S %w %W %x %X %y %Y %f %z %Z"
        output = u"جمعه جمعه اردیبهشت اردیبهشت جمعه ۲۳ اردیبهشت ۹۰, ۰۰:۰۰:۰۰ ۲۳ ۰۰ ۱۲ ۰۵۴ ۰۲ ۰۰ قبل از ظهر ۰۰ ۶ ۸ ۱۳۹۰/۰۲/۲۳ ۰۰:۰۰:۰۰ ۹۰ ۱۳۹۰ ۰۰۰۰۰۰  "
        self.assertEqual(s.strftime(string_format), output)

        dt = jdatetime.datetime(1390, 2, 23, 12, 13, 14, 1, locale='fa_IR')
        unicode_format = "%a %A %b %B %c %d %H %I %j %m %M %p %S %w %W %x %X %y %Y %f"
        output = u"جمعه جمعه اردیبهشت اردیبهشت جمعه ۲۳ اردیبهشت ۹۰, ۱۲:۱۳:۱۴ ۲۳ ۱۲ ۱۲ ۰۵۴ ۰۲ ۱۳ بعد از ظهر ۱۴ ۶ ۸ ۱۳۹۰/۰۲/۲۳ ۱۲:۱۳:۱۴ ۹۰ ۱۳۹۰ ۰۰۰۰۰۱"

        self.assertEqual(dt.strftime(unicode_format), output)

        string_format = u"سال = %y، ماه = %m، ﺭﻭﺯ = %d"
        output = u'سال = ۹۰، ماه = ۰۲، ﺭﻭﺯ = ۲۳'
        self.assertEqual(dt.strftime(string_format), output)
예제 #20
0
    def test_replace(self):
        dt = jdatetime.datetime.today()
        args = {
            'year': 1390,
            'month': 12,
            'day': 1,
            'hour': 13,
            'minute': 14,
            'second': 15,
            'microsecond': 1233
        }
        dtr = dt.replace(**args)
        dtn = jdatetime.datetime(1390, 12, 1, 13, 14, 15, 1233)

        self.assertEqual(True, dtr == dtn)
예제 #21
0
파일: run.py 프로젝트: arianbakh/Accidents
def _get_datetime(date, time, year_month):
    if date and time:
        if len(date) == 8:
            year = int(date.strip()[:4])
            month = int(date.strip()[4:6])
        else:
            year = int(year_month.split('.')[0])
            month = int(year_month.split('.')[1])
        day = int(date.strip()[-2:])
        if len(time) < 4:
            time = '0' * (4 - len(time)) + time
        hour = int(time[:2])
        minute = int(time[2:])
        return jdatetime.datetime(year, month, day, hour, minute).togregorian()
    return None
예제 #22
0
def update_alarm_time(alarm):
    session = session_factory().object_session(alarm)
    target_alarm = session.query(DataBaseAlarm).filter_by(id=alarm.id).first()
    temp_time = target_alarm.start_time.split(":")
    date_time = jdatetime.datetime(int(temp_time[0]), int(temp_time[1]),
                                   int(temp_time[2]), int(temp_time[3]),
                                   int(temp_time[4]))
    date_time = date_time + jdatetime.timedelta(
        minutes=int(alarm.repeat_period))
    target_alarm.start_time = "{}:{}:{}:{}:{}".format(date_time.year,
                                                      date_time.month,
                                                      date_time.day,
                                                      date_time.hour,
                                                      date_time.minute)
    session.commit()
    session.close()
예제 #23
0
파일: factories.py 프로젝트: b-liva/factor
class TenderFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Tender

    owner = factory.SubFactory(UserFactory)
    order = factory.SubFactory(RequestFactory)
    customer = factory.SubFactory(CustomerFactory)
    title = factory.LazyAttribute(lambda o: faker.word())
    number = factory.LazyAttribute(lambda o: str(faker.random_int()))
    due_date_fa = jdatetime.datetime(1400, 7, 10, 20, 12, 14)
    collateral = factory.LazyAttribute(lambda o: str(faker.random_int()))
    collateral_type = factory.SubFactory(CollateralTypeFactory)
    assessment = factory.LazyAttribute(lambda o: str(faker.random_int()))
    payment_type = factory.SubFactory(PaymentTypeFactory)
    prepayment = factory.LazyAttribute(lambda o: str(faker.random_int()))
    contact = factory.LazyAttribute(lambda o: faker.text())
예제 #24
0
def middle_east_parsed_date(text_date, kwargs):
    """
    :param text_date:
    :param kwargs: format : %d-%m-%Y for 12-7-1397.
    :return:
    """
    dict_month_numeric = dict(
        (v, k) for k, v in enumerate(calendar.month_name))
    dict_month_abbr_numeric = dict(
        (v, k) for k, v in enumerate(calendar.month_abbr))

    day = -1
    month = -1
    year = -1
    default_format = ["%d", "%m", "%Y"]
    tsplit = split_non_alpha(text_date)
    if "format" in kwargs:
        format = kwargs["format"]
    else:
        format = default_format
    if len(tsplit) != len(default_format):
        #TODO: likely split characters next to each other 29101394
        return None
    for idx in range(0, len(tsplit)):
        item = tsplit[idx]
        if not isinstance(item, int) and not isinstance(item, float):
            item = item.capitalize().strip()
            if item in dict_month_numeric:
                item = dict_month_numeric[item]
            elif item in dict_month_abbr_numeric:
                item = dict_month_abbr_numeric[item]
        f_value = format[idx]
        if f_value == "%d":
            day = int(item)
        elif f_value == "%m":
            month = int(item)
        elif f_value == "%Y":
            year = int(item)

    if month > 0 and day > 0 and year > 0:
        if year < 1410:
            jd = jdatetime.datetime(year, month, day)
            return jd.togregorian()
        if year < 1500:
            um = HijriDate(year, month, day)
            return datetime(um.year_gr, um.month_gr, um.day_gr)
    return None
예제 #25
0
 def test_as_locale_returns_same_datetime_with_specified_locale(self):
     jdt_en = jdatetime.datetime(1397,
                                 4,
                                 23,
                                 11,
                                 47,
                                 30,
                                 40,
                                 locale='en_US')
     jdt_fa = jdt_en.aslocale('fa_IR')
     self.assertEqual(jdt_fa.year, 1397)
     self.assertEqual(jdt_fa.month, 4)
     self.assertEqual(jdt_fa.day, 23)
     self.assertEqual(jdt_fa.hour, 11)
     self.assertEqual(jdt_fa.minute, 47)
     self.assertEqual(jdt_fa.second, 30)
     self.assertEqual(jdt_fa.microsecond, 40)
     self.assertEqual(jdt_fa.locale, 'fa_IR')
예제 #26
0
    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)
        self.assertEqual(False, today > today)
        self.assertEqual(False, today < today)
        self.assertEqual(True, today >= 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)
예제 #27
0
def sth(request):
    my_time = jdatetime.datetime(1397, 1, 1, 13, 10, 10)
    print(my_time)
    print(request)
    print(request.GET)
    print(request.user)
    # if request.user.username != 'admin':
    # 	return HttpResponse('WOW. not welcome')
    response = ''
    for post in Post.objects.filter(author__name='alireza'):
        response += str(my_time.date())
        response += '<h1>' + post.title + '</h1>' + '<div>' + post.text + '</div>'
        for tag in post.tags.all():
            response += '<div style="color:red">' + tag.name + '</div>'
        response += '<div style="height:100px"></div>'
    for tag in Tag.objects.all():
        response += '<br>' + tag.name
    print(response)
    return HttpResponse(response, status=200)
예제 #28
0
    def parse_date(self, datetime_str):
        "Take a jalali str and convert it to jalali date"
        datetime_str = smart_str(datetime_str)
        print('parse_date: ', datetime_str)
        if datetime_str is None:
            return None

        # get timezone if available
        if '+' in datetime_str:
            datetime_str, tz = datetime_str.split('+', maxsplit=1)
            try:
                tz = datetime.datetime.strptime('+'+tz, '%z').tzinfo
            except ValueError:
                raise exceptions.ValidationError(
                    self.error_messages['invalid'])
        else:
            tz = None
        kwargs = {'tzinfo': tz}

        if '.' in datetime_str:  # split usecs
            try:
                datetime_str, usecs = datetime_str.split('.')
                kwargs['microsecond'] = int(usecs)
            except ValueError:
                raise exceptions.ValidationError(
                    self.error_messages['invalid'])
        else:
            kwargs['microsecond'] = 0

        try:
            date_str, time_str = datetime_str.split(' ')  # split date and time
            time_args = list(map(int, time_str.split(':')))
            if len(time_args) == 3:  # seconds are present
                kwargs['hour'], kwargs['minute'], kwargs['seconds'] = time_args
            elif len(time_args) == 2:  # seconds are not present
                kwargs['hour'], kwargs['minute'] = time_args
                kwargs['seconds'] = 0
            date_args = list(map(int, date_str.split('-')))
            kwargs['year'], kwargs['month'], kwargs['day'] = date_args
            print('parse_date', kwargs)
            return jdatetime.datetime(**kwargs)
        except ValueError:
            raise exceptions.ValidationError(self.error_messages['invalid'])
예제 #29
0
def insertToConductor(username, password, items):
    if checkForAdmin(username, password):
        for i in items:
            item = items[i]
            splitedTime = item.get("time").split(":")
            splitedDate = item.get("date").split("/")
            date = jdt.datetime(int(splitedDate[0]), int(splitedDate[1]),
                                int(splitedDate[2]), int(splitedTime[0]),
                                int(splitedTime[1]))
            date = date.togregorian()
            newItem = models.ConductorItem(name=item.get("name"),
                                           desc=item.get("desc"),
                                           startTime=date,
                                           duration=int(item.get("duration")),
                                           itemType=item.get("type"))
            try:
                newItem.save()
            except Exception as e:
                createLog("Admin failed to insert new item to conductor", {
                    "error": e,
                    "items": items
                })
                return {
                    "result": False,
                    "code": 607,
                    "desc": str(e) + enums.getErrors(607)
                }
        createLog("Admin inserted items to conductor successfully", {
            "items": items,
            "admin": username
        })
        return {
            "result": True,
            "code": 200,
            "desc": "items inserted successfully"
        }
    else:
        createLog(
            "User with this username tried to insert items to conductor ", {
                "username": username,
                "items": items
            })
        return {"result": False, "code": 666, "desc": enums.getErrors(666)}
예제 #30
0
    def test_timezone(self):
        current_timezone = timezone.get_current_timezone()
        jdt1 = jdatetime.datetime(1392, 3, 12, 10, 22, 23, 240000)
        jdt1 = current_timezone.localize(jdt1)

        new_bartime = BarTime.objects.create(name="with timezone",
                                             datetime=jdt1)
        self.assertTrue(hasattr(new_bartime.datetime.tzinfo, 'localize'))
        self.assertEqual(
            new_bartime.datetime.tzinfo.utcoffset(new_bartime.datetime),
            datetime.timedelta(seconds=16200),
        )

        k = BarTime.objects.filter(datetime=jdt1)
        self.assertTrue(hasattr(k[0].datetime.tzinfo, 'localize'))
        self.assertEqual(
            k[0].datetime.tzinfo.utcoffset(k[0].datetime),
            datetime.timedelta(seconds=16200),
        )
예제 #31
0
def editConductorItem(username, password, items):
    if checkForAdmin(username, password):
        number = 0
        for i in items:
            item = items[i]
            db_item = getConductorItemById(item.get("id"))
            splitedTime = item.get("time").split(":")
            splitedDate = item.get("date").split("/")
            date = jdt.datetime(int(splitedDate[0]), int(splitedDate[1]),
                                int(splitedDate[2]), int(splitedTime[0]),
                                int(splitedTime[1]))
            date = date.togregorian()
            updatedRows = db_item.update(startTime=date,
                                         name=item.get('name'),
                                         desc=item.get('desc'),
                                         duration=item.get('duration'),
                                         itemType=item.get('type'))
            number = number + updatedRows
        if number == len(items):
            createLog("Admin edited items in conductor successfully", items)
            return {
                "result": True,
                "code": 200,
                "desc": "all items updated successfully"
            }
        else:
            createLog("Admin failed to update some items in conductor", {
                "number": str(len(items) - int(number)),
                "items": items
            })
            return {
                "result": True,
                "code": 608,
                "desc": str(len(items) - int(number)) + enums.getErrors(608)
            }
    else:
        createLog("User with this username tried to edit items in conductor ",
                  {
                      "username": username,
                      "items": items
                  })
        return {"result": False, "code": 666, "desc": "User is not admin"}
예제 #32
0
def get_formatted_jdatetime(datetime_object, object_type="datetime", show_seconds=True):
    year = datetime_object.year
    month = datetime_object.month
    day = datetime_object.day
    if object_type.lower() == "datetime":
        jobject = datetime(
            year,
            month,
            day,
            datetime_object.hour,
            datetime_object.minute,
            datetime_object.second,
            locale="fa_IR",
        )
        format_rule = "%a, %d %b %Y %H:%M:%S" if show_seconds else "%a, %d %b %Y %H:%M"
        return jobject.strftime(format_rule)
    elif object_type.lower() == "date":
        jobject = date(year, month, day, locale="fa_IR")
        return jobject.strftime("%a, %d %b %Y")
    else:
        raise ValueError("Unexpected argument was passed")
예제 #33
0
파일: crawler.py 프로젝트: amirsaeidy/cdn
def stockscrawler(id):
    driver = webdriver.Chrome(executable_path="/home/amir/ChromeDriver")
    # driver = webdriver.Chrome(executable_path="/home/amirs/chromedriver")

    ll = driver.execute_script('return ClosingPriceData')
    Fa_Date = driver.find_element_by_css_selector("#MainBox > div.header.bigheader > span:nth-child(3)").text
    Fa_Date = (int(Fa_Date.split("/")[0]), int(Fa_Date.split("/")[1]), int(Fa_Date.split("/")[2]))
    
    for i in range(len(ll)):

        Price = ll[i][2]
        Volume = ll[i][9]
        Transactions_Value = ll[i][10]
        Time = jdatetime.datetime(Fa_Date[0], Fa_Date[1], Fa_Date[2], int(ll[i][12][:-4]), int(ll[i][12][-4:-2]),
                                        int(ll[i][12][-2:])).strftime("%Y-%m-%d %H:%M:%S.%f")

        Symbols_Transactions.objects.create(
                Symbol = id
                DateTime = Time
                Price = Price
                Volume = Volume
                Value = Value
            )
예제 #34
0
    def formatday(self, day, events):
        events_per_day = events.filter(date__day=day)
        d = ''
        for event in events_per_day:
            d += f'<li> {event.get_html_url} </li>'

        if day != 0:
            hijri_date = convert.Gregorian(day=day,
                                           month=self.month,
                                           year=self.year).to_hijri()
            jd = jdatetime.date.fromgregorian(day=day,
                                              month=self.month,
                                              year=self.year)

            jal_month = jdatetime.GregorianToJalali(self.year, self.month, 15)
            jal_month = jdatetime.datetime(jal_month.jyear, jal_month.jmonth,
                                           jal_month.jday).strftime(' | %B %Y')

            hij_month = convert.Gregorian(self.year, self.month, 15).to_hijri()
            hij_month = convert.Hijri(hij_month.year, hij_month.month,
                                      hij_month.day)

            return f"<span id='jal-month' style='display: none;'>{jal_month}</span><span id='hij-month' style='display:none;'> | {hij_month.month_name()} {hij_month.year}</span><td title='{self.year}-{self.month}-{day} gregorian and {jd.year}-{jd.month}-{jd.day} shamsi and {hijri_date.year}-{hijri_date.month}-{hijri_date.day} ghamari' id='{self.year}-{self.month}-{day}'><span class='{day} date'>{day}</span><br><span class='{jd.day} jalali-day'>{jd.day}ش</span><br><span class='hijri-date {hijri_date.day}'>{hijri_date.day}ه</span><ul> {d} </ul></td>"
        return '<td></td>'
예제 #35
0
파일: views.py 프로젝트: inaseri/test
def vecation(request):
    if request.method == 'POST':
        dateOfDesc = request.POST.get('dateOfDesc')
        dateOfDescSplited = dateOfDesc.split("/")

        # this three lines use for get month and year of date that selected
        monthNumber = int(dateOfDescSplited[1])
        yearNumber = int(dateOfDescSplited[0])
        dayNumber = int(dateOfDescSplited[2])

        # this tow lines use for convert persian date to gregorian
        dateOfDesc = jdatetime.datetime(yearNumber, monthNumber, dayNumber)
        dateOfDesc = dateOfDesc.togregorian()

        desc = request.POST.get('desc')
        dateOfDesc = dateOfDesc.date()

        try:
            Times.objects.filter(owner=request.user,
                                 date=dateOfDesc).update(desc=desc)
        except:
            pass

    return render(request, THEMPLATE_NAME + "/vacation.html")
예제 #36
0
def xlsx(request, filtering, query_start_year, query_start_month,
         query_start_day, query_end_year, query_end_month, query_end_day,
         operation_type):
    """

    Args:
        request:
        filtering:
        query_start_year:
        query_start_month:
        query_start_day:
        query_end_year:
        query_end_month:
        query_end_day:
        operation_type:

    Returns:


    """
    try:

        query_start_date = jdatetime.date(query_start_year, query_start_month,
                                          query_start_day) - timedelta(days=1)
        # because quering from data base we should consider filter data via utc time
        QUERY_START_DATE = jdatetime.datetime(
            query_start_date.year, query_start_date.month,
            query_start_date.day, 19, 30).astimezone(pytz.timezone('UTC'))
        QUERY_END_DATE = jdatetime.datetime(query_end_year, query_end_month,
                                            query_end_day, 19, 30).astimezone(
                                                pytz.timezone('UTC'))
        if QUERY_END_DATE < QUERY_START_DATE:
            return render(request, 'acc/hospital/index.html', {
                'date_error': 'بازه زمانی وارد شده نا معتبر است',
                'flag': 1
            })  # , 'date': jdatetime.date.today(),

        # Create Excel

        # chart_data = {
        #     'total_green': 0,
        #     'total_yellow': 0,
        #     'total_red': 0,
        #     'total_blue': 0,
        # }

        table_rows = []
        for t, model_hist in model_dict.items():
            if t == 'Report':
                continue
            for model in model_hist:
                report_query = model[0].objects.filter(
                    date__gte=QUERY_START_DATE).filter(
                        date__lte=QUERY_END_DATE)
                if Group.objects.get(
                        name='hospital') in request.user.groups.all():  # admin
                    report_query = report_query.filter(
                        request__hospital__user__id__exact=request.user.id)
                if filtering == 'recal':
                    report_query = report_query.filter(is_recal=True)
                for obj in report_query:
                    row = {
                        'state_name': obj.device.hospital.city.state.name,
                        'city_name': obj.device.hospital.city.name,
                        'hospital_name': obj.device.hospital.name,
                        'section_name': obj.device.section.name,
                        'device_type_name': obj.device.name.type.name,
                        'device_creator_name': obj.device.name.creator.name,
                        'device_name': obj.device.name.name,
                        'device_serial_number': obj.device.serial_number
                    }
                    if str(obj.device.property_number) != 'None':
                        row['device_property_number'] = obj.device.property_number
                    else:
                        row['device_property_number'] = '-'
                    row['test_status'] = obj.status.status
                    row['test_time'] = obj.date.strftime("%Y-%m-%d")
                    if obj.status.id != 4:
                        row['test_licence_number'] = obj.licence.number
                    else:
                        row['test_licence_number'] = '-'
                    if t == 'MonitorSpo2':
                        row['test_comment'] = '-SPO2-' + obj.totalcomment
                    elif t == 'MonitorECG':
                        row['test_comment'] = '-ECG-' + obj.totalcomment
                    elif t == 'MonitorNIBP':
                        row['test_comment'] = '-NIBP-' + obj.totalcomment
                    elif t == 'MonitorSafety':
                        row['test_comment'] = '-Safety-' + obj.totalcomment
                    else:
                        row['test_comment'] = obj.totalcomment

                    row['test_status_id'] = obj.status.id  # dor excel row color

                    try:
                        encode_obj = Encode.objects.get(
                            hospital=obj.device.hospital)

                        row['url'] = 'https://{dl_domain}/reports/pdf/{state}/{city}/{hosp}/{req}/{section}/{device_type}/{' \
                                     'licence}.pdf'.format(
                            dl_domain=dl_domain_name,
                            state=obj.device.hospital.city.state.eng_name,
                            city=obj.device.hospital.city.eng_name,
                            hosp=str(obj.device.hospital.user.id) + '_' + encode_obj.name,
                            req=obj.request.number,
                            section=obj.device.section.eng_name,
                            device_type=t,
                            licence=obj.licence.number,
                        )
                    except:
                        row['url'] = 'https://panel.azmasaba.ir'
                    table_rows.append(row)

        table_header_list = AdExcelArg.objects.all().order_by('id')
        table_header = (str(table_header_list[1]), str(table_header_list[2]),
                        str(table_header_list[3]), str(table_header_list[4]),
                        str(table_header_list[5]), str(table_header_list[6]),
                        str(table_header_list[7]), str(table_header_list[8]),
                        str(table_header_list[9]), str(table_header_list[10]),
                        str(table_header_list[11]), str(table_header_list[12]),
                        str(table_header_list[13]), str(table_header_list[14]),
                        str(table_header_list[15]), 'PDF')

        # chart_data['total_green'] = len(report_query.filter(status__id=1))
        # chart_data['total_yellow'] = len(report_query.filter(status__id=2))
        # chart_data['total_red'] = len(report_query.filter(status__id=3))
        # chart_data['total_blue'] = len(report_query.filter(status__id=4))
        # for index, query in enumerate(query_list):

        if operation_type == 'download':

            output = io.BytesIO()
            wb = xlsxwriter.Workbook(output)
            ws = wb.add_worksheet(name='Data')
            chart_ws = wb.add_worksheet(name='Charts')

            chart_ws.right_to_left()
            ws.right_to_left()

            ws.set_default_row(height=40)
            ws.set_column(0, 15, 17)

            # first row

            table_header_format = wb.add_format({
                'font_size': 11,
                'align': 'center',
                'valign': 'vcenter',
                'bottom': True,
                'left': True
            })

            ws.write_row(row=0,
                         col=0,
                         data=table_header,
                         cell_format=table_header_format)
            # Patterns
            green_row_format = wb.add_format(  # accept
                {'font_size': 11, 'align': 'center', 'valign': 'vcenter', 'pattern': 1, 'bg_color': 'green',
                 'bottom': True,
                 'left': True})
            yellow_row_format = wb.add_format(  # conditional
                {'font_size': 11, 'align': 'center', 'valign': 'vcenter', 'pattern': 1, 'bg_color': 'yellow',
                 'bottom': True,
                 'left': True})
            red_row_format = wb.add_format(  # reject
                {'font_size': 11, 'align': 'center', 'valign': 'vcenter', 'pattern': 1, 'bg_color': 'red',
                 'bottom': True,
                 'left': True})
            cursor = 1

            for row in table_rows:
                # if (modelobj[i].device.hospital.user == request.user):
                # Assign Status
                if row['test_status_id'] == 1:  # accept
                    row_format = green_row_format
                elif row['test_status_id'] == 2:  # conditional
                    row_format = yellow_row_format
                elif row['test_status_id'] == 3:  # conditional
                    row_format = red_row_format
                else:
                    row_format = table_header_format

                row_data = (
                    cursor,
                    row['state_name'],  # ostan
                    row['city_name'],  # shahr
                    row['hospital_name'],  # name moshtari
                    row['section_name'],  # mahale esteqrar
                    row['device_type_name'],  # mahsul
                    row['device_creator_name'],  # tolid konande
                    row['device_name'],  # model
                    row['device_serial_number'],  # shoamre serial
                    row['device_property_number'],  # kode amval
                    row['test_status'],  # vaziate azmoon
                    row['test_time'],  # tarikh calibration
                    str(table_header_list[0]),  # etebare calibration
                    row['test_licence_number'],  # shomare govahi
                    row['test_comment'],  # tozihat
                )
                ws.write_row(row=cursor,
                             col=0,
                             data=row_data,
                             cell_format=row_format)
                ws.write_url(row=cursor,
                             col=len(row_data),
                             url=row['url'],
                             cell_format=row_format,
                             string='show',
                             tip='Downlaod PDF')

                cursor += 1
            wb.close()
            output.seek(0)
            filename = f'Azma_Saba.ExcelReport.{str(jdatetime.date.today()).split()[0]}.xlsx'
            response = HttpResponse(
                output,
                content_type=
                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            )
            response[
                'Content-Disposition'] = 'attachment; filename=%s' % filename
            return response

        elif operation_type == 'show':  # display table
            # avatar_url = UserProfile.objects.get(
            #     id=1).avatar.url  # admin user_profile

            # chart = [0, 0, 0, 0]
            # if Group.objects.get(name='hospital') in request.user.groups.all():
            #     request_list = Request.objects.filter(
            #         hospital__user=request.user).order_by('date')
            #     template_name = 'acc/hospital/index.html'
            # else:
            #     request_list = Request.objects.all().order_by('date')
            #     template_name = 'acc/admin/index.html'

            # for obj in query_list:
            #     chart[0] += len(obj.filter(status__id=1))
            #     chart[1] += len(obj.filter(status__id=2))
            #     chart[2] += len(obj.filter(status__id=3))
            #     chart[3] += len(obj.filter(status__id=4))

            # for req in request_list:
            #     req.date = req.date.today()

            pass_data = {
                'table_header': table_header,
                'table_rows': table_rows,
                # 'request': request_list, 'avatar_url': avatar_url,
                # 'user_name': request.user.first_name, 'chart': chart
            }
            if Group.objects.get(name='admin') in request.user.groups.all():
                pass_data['admin'] = 1
            return render(request, 'acc/hospital/table.html', pass_data)
    except Exception as e:
        return HttpResponse('{}'.format(e))
예제 #37
0
def parse(fileName):
    certaintyScore = 100  # This will be decreased by percentages if signs of uncertainty show
    # Get document ID
    file_chunks = fileName.split('/')
    last_chunk = file_chunks[len(file_chunks) - 1]
    document_id = last_chunk[:len(last_chunk) -
                             5]  # Remove the .html at the end
    print('Document ID:', document_id)
    # Grab file contents
    htmlFile = open(fileName)
    html = htmlFile.read()
    htmlFile.close()
    # Extract all pertinent sections
    soup = BeautifulSoup(html, 'html.parser')
    # This extracts the declaration which doesn't include the document information section. This is where the names occur.
    declaration = ''
    try:
        declaration = soup.find(class_='Jus').contents[0]
    except:
        print('Malformed file')
        return
    # This extracts where the national ID is sometimes stored
    title = ''
    try:
        title = soup.find(id='cphMain_lblNewsTitle').contents[0]
    except:
        title = ''
    # These are all the extracted text chunks functions will have available to parse
    contents = {'title': title, 'declaration': declaration}
    # Company ID retreival
    companyId = nationalid.parse_id(contents['title'])
    if DEBUG:
        print('National ID (title):', companyId)
    if companyId == None:
        certaintyScore *= 0.8  # Proof of concept not good
        companyId = nationalid.parse_id(
            contents['declaration']
        )  # This finds a company ID in the text but it might be referencing another corporation
    if DEBUG:
        print('National ID (declaration):',
              nationalid.parse_id(contents['declaration']))
    # Various date retreival
    try:
        dates = dateextract.parse_dates(html, contents)
    except:
        print('Malformed file. Returning early')
        return
    # Name retreival
    names = get_names(contents)
    names += double_tap_names(contents)
    names += namehelper.parse_name_sandwhich(contents)
    cleaned_names = clean(names)
    # Now we get the document date in English dates
    persian_date = dates['registration_date']
    date_data = persian_date.split('/')
    document_date = jdatetime.datetime(int(date_data[0]), int(date_data[1]),
                                       int(date_data[2])).togregorian()
    document_timestamp = time.mktime(document_date.timetuple())
    print(document_timestamp)
    return {
        'document_id': document_id,
        'document_date': document_timestamp,
        'company_id': translator.convert(companyId),
        's3_path': fileName[6:],
        'names': cleaned_names,
        'dates': dates,
        'raw_title': contents['title'],
        'raw_body': contents['declaration'],
        'certainty_score': certaintyScore,
        'parser_version': 1
    }
예제 #38
0
 def test_datetime_to_str(self):
     date = jdatetime.datetime(1394, 1, 1, 0, 0, 0)
     self.assertEqual(str(date), "1394-01-01 00:00:00")
예제 #39
0
 def test_datetime_to_str(self):
     date = jdatetime.datetime(1394, 1, 1, 0, 0, 0)
     self.assertEqual(str(date), "1394-01-01 00:00:00")
예제 #40
0
파일: test.py 프로젝트: knv/python-jalali
 def test_replace(self):
     dt  = jdatetime.datetime.today()
     dtr = dt.replace(year=1390, month=12, day=1, hour=13, minute=14, second=15, microsecond = 1233)
     dtn = jdatetime.datetime(1390, 12, 1, 13, 14, 15, 1233)
     
     self.assertEqual(True, dtr == dtn )
예제 #41
0
 def test_timestamp_implemented(self):
     teh = TehranTime()
     jdt = jdatetime.datetime(1397, 4, 23, 11, 47, 30, 40, tzinfo=teh)
     self.assertEqual(jdt.timestamp(), 1531556250.00004)
예제 #42
0
    def test_isoformat_custom_sep(self):
        jdt = jdatetime.datetime(1398, 4, 11)
        jiso = jdt.isoformat('M')

        self.assertAlmostEqual(jiso, '1398-04-11M00:00:00')
예제 #43
0
    def test_combine(self):
        t = jdatetime.time(12, 13, 14)
        d = jdatetime.date(1390, 4, 5)
        dt = jdatetime.datetime(1390, 4, 5, 12, 13, 14)

        self.assertEqual(True, jdatetime.datetime.combine(d, t) == dt)
예제 #44
0
 def test_timestamp_not_implemented(self):
     teh = TehranTime()
     jdt = jdatetime.datetime(1397, 4, 23, 11, 47, 30, 40, tzinfo=teh)
     with self.assertRaises(NotImplementedError):
         jdt.timestamp()
예제 #45
0
    def parse_date(self, datetime_obj):
        "Take a datetime object and convert it to jalali date"

        if isinstance(datetime_obj, datetime.datetime):
            try:
                if datetime_obj.year < 1700:
                    return jdatetime.datetime(
                        datetime_obj.year, datetime_obj.month,
                        datetime_obj.day, datetime_obj.hour,
                        datetime_obj.minute, datetime_obj.second,
                        datetime_obj.microsecond, datetime_obj.tzinfo)
                else:
                    return jdatetime.datetime.fromgregorian(
                        datetime=datetime_obj)
            except ValueError:
                raise exceptions.ValidationError(
                    self.error_messages['invalid'])
        if isinstance(datetime_obj, datetime.date):
            try:
                if datetime_obj.year < 1700:
                    return jdatetime.datetime(datetime_obj.year,
                                              datetime_obj.month,
                                              datetime_obj.day)
                else:
                    return jdatetime.datetime.fromgregorian(date=datetime_obj)
            except ValueError:
                raise exceptions.ValidationError(
                    self.error_messages['invalid'])

        # Attempt to parse a datetime:
        datetime_obj = smart_str(datetime_obj)
        if not datetime_obj:
            return None
        # split usecs, because they are not recognized by strptime.
        if '.' in datetime_obj:
            try:
                datetime_obj, usecs = datetime_obj.split('.')
                if '+' in usecs:
                    usecs, tz = usecs.split('+')
                usecs = int(usecs)
            except ValueError:
                raise exceptions.ValidationError(
                    self.error_messages['invalid'])
        else:
            usecs = 0
        kwargs = {'microsecond': usecs}
        try:  # Seconds are optional, so try converting seconds first.
            t = time.strptime(datetime_obj, '%Y-%m-%d %H:%M:%S')
            if t.tm_year > 1700:
                return datetime.datetime(
                    *time.strptime(datetime_obj, '%Y-%m-%d %H:%M:%S')[:6],
                    **kwargs)
            else:
                return jdatetime.datetime(
                    *time.strptime(datetime_obj, '%Y-%m-%d %H:%M:%S')[:6],
                    **kwargs)

        except ValueError:
            try:  # Try without seconds.
                t = time.strptime(datetime_obj, '%Y-%m-%d %H:%M')
                if t.tm_year > 1700:
                    return datetime.datetime(
                        *time.strptime(datetime_obj, '%Y-%m-%d %H:%M')[:5],
                        **kwargs)
                else:
                    return jdatetime.datetime(
                        *time.strptime(datetime_obj, '%Y-%m-%d %H:%M')[:5],
                        **kwargs)

            except ValueError:  # Try without hour/minutes/seconds.
                try:
                    t = time.strptime(datetime_obj, '%Y-%m-%d')[:3]
                    if t[0] > 1700:
                        return datetime.datetime(
                            *time.strptime(datetime_obj, '%Y-%m-%d')[:3],
                            **kwargs)
                    else:
                        return jdatetime.datetime(
                            *time.strptime(datetime_obj, '%Y-%m-%d')[:3],
                            **kwargs)
                except ValueError:
                    raise exceptions.ValidationError(
                        self.error_messages['invalid'])
예제 #46
0
 def test_timestamp_implemented(self):
     teh = TehranTime()
     jdt = jdatetime.datetime(1397, 4, 23, 11, 47, 30, 40, tzinfo=teh)
     self.assertEqual(jdt.timestamp(), 1531556250.00004)
예제 #47
0
 def test_timetuple(self):
     jdt = jdatetime.datetime(1397, 4, 23, 11, 47, 30, 40)
     self.assertEqual(
         jdt.timetuple(),
         time.struct_time((2018, 7, 14, 11, 47, 30, 5, 195, -1)),
     )
예제 #48
0
 def test_datetimes_with_different_locales_are_not_equal(self):
     dt_en = jdatetime.datetime(2018, 4, 15, 0, 0, 0, locale='en_US')
     dt_fa = jdatetime.datetime(2018, 4, 15, 0, 0, 0, locale='fa_IR')
     self.assertNotEqual(dt_en, dt_fa)
예제 #49
0
 def setUp(self):
     self.date_string = "1380-08-02"
     self.datetime = jdatetime.datetime(1380,8,2,12,12,12)
     self.bar_time = BarTime(name="foo time", datetime=self.datetime)
     self.bar_time.save()
예제 #50
0
    def test_isoformat_bad_sep(self):
        jdt = jdatetime.datetime(1398, 4, 11)

        for t in ['dummy', 123, 123.123, (1, 2, 3), [1, 2, 3]]:
            with self.assertRaises(AssertionError):
                jdt.isoformat(t)
예제 #51
0
    def test_datetime(self):
        d = jdatetime.datetime(1390, 1, 2, 12, 13, 14)

        self.assertEqual(True, d.time() == jdatetime.time(12, 13, 14))
        self.assertEqual(True, d.date() == jdatetime.date(1390, 1, 2))
예제 #52
0
 def setUp(self):
     self.date_string = "1380-08-02"
     self.datetime = jdatetime.datetime(1380, 8, 2, 12, 12, 12)
     self.bar_time = BarTime(name="foo time", datetime=self.datetime)
     self.bar_time.save()
예제 #53
0
파일: test.py 프로젝트: knv/python-jalali
    def test_strptime(self):
        dt1 = jdatetime.datetime.strptime("1363-6-6 12:13:14","%Y-%m-%d %H:%M:%S")
        dt2 = jdatetime.datetime(1363, 6 , 6 , 12, 13, 14)

        self.assertEqual(True, dt1 == dt2)
예제 #54
0
def Next_month(sourcedate):
    month = sourcedate.month
    year = sourcedate.year + month // 12
    month = month % 12 + 1
    day = min(sourcedate.day, calendar.monthrange(year, month)[1])
    return datetime(year, month, day)
예제 #55
0
 def test_timestamp_not_implemented(self):
     teh = TehranTime()
     jdt = jdatetime.datetime(1397, 4, 23, 11, 47, 30, 40, tzinfo=teh)
     with self.assertRaises(NotImplementedError):
         jdt.timestamp()
예제 #56
0
    def to_python(self, value):
        if value is None:
            return value
        if isinstance(value, datetime.datetime):
            try:
                if value.year < 1700:
                    return jdatetime.datetime(
                        value.year,
                        value.month,
                        value.day,
                        value.hour,
                        value.minute,
                        value.second,
                        value.microsecond,
                        value.tzinfo,
                    )
                else:
                    return jdatetime.datetime.fromgregorian(datetime=value)
            except ValueError:
                raise exceptions.ValidationError(self.error_messages["invalid"])
        if isinstance(value, datetime.date):
            try:
                if value.year < 1700:
                    return jdatetime.datetime(value.year, value.month, value.day)
                else:
                    return jdatetime.datetime.fromgregorian(date=value)
            except ValueError:
                raise exceptions.ValidationError(self.error_messages["invalid"])
        if isinstance(value, jdatetime.datetime):
            return value
        if isinstance(value, jdatetime.date):
            try:
                d = jdatetime.datetime(value.year, value.month, value.day)
            except ValueError:
                raise exceptions.ValidationError(self.error_messages["invalid"])
            return d

        # Attempt to parse a datetime:
        value = smart_str(value)
        # split usecs, because they are not recognized by strptime.
        if "." in value:
            try:
                value, usecs = value.split(".")
                usecs = int(usecs)
            except ValueError:
                raise exceptions.ValidationError(self.error_messages["invalid"])
        else:
            usecs = 0
        kwargs = {"microsecond": usecs}
        try:  # Seconds are optional, so try converting seconds first.
            t = time.strptime(value, "%Y-%m-%d %H:%M:%S")
            if t.tm_year > 1700:
                return datetime.datetime(*time.strptime(value, "%Y-%m-%d %H:%M:%S")[:6], **kwargs)
            else:
                return jdatetime.datetime(*time.strptime(value, "%Y-%m-%d %H:%M:%S")[:6], **kwargs)

        except ValueError:
            try:  # Try without seconds.
                t = time.strptime(value, "%Y-%m-%d %H:%M")
                if t.tm_year > 1700:
                    return datetime.datetime(*time.strptime(value, "%Y-%m-%d %H:%M")[:5], **kwargs)
                else:
                    return jdatetime.datetime(*time.strptime(value, "%Y-%m-%d %H:%M")[:5], **kwargs)

            except ValueError:  # Try without hour/minutes/seconds.
                try:
                    t = time.strptime(value, "%Y-%m-%d")[:3]
                    if t[0] > 1700:
                        return datetime.datetime(*time.strptime(value, "%Y-%m-%d")[:3], **kwargs)
                    else:
                        return jdatetime.datetime(*time.strptime(value, "%Y-%m-%d")[:3], **kwargs)
                except ValueError:
                    raise exceptions.ValidationError(self.error_messages["invalid"])
예제 #57
0
 def test_timetuple(self):
     jdt = jdatetime.datetime(1397, 4, 23, 11, 47, 30, 40)
     self.assertEqual(
         jdt.timetuple(),
         time.struct_time((2018, 7, 14, 11, 47, 30, 5, 195, -1)),
     )
예제 #58
0
    def test_diffrent_saving(self):
        jd_model = jDateModel(date="1391-01-01")
        jd_model.save()

        jd_model = jDateModel(date=datetime.datetime.now())
        jd_model.save()

        # jd_model = jDateModel()
        # jd_model.save()

        jd_model = jDateModel(date=jdatetime.datetime.now())
        jd_model.save()

        # to_python
        jdt_model = jDateTimeModel(date_time="1391-01-01")
        # TODO: Find the correct exceptions
        # with self.assertRaises(Exception):
        #    jdt_model.date_time = None

        jdt_model.date_time = datetime.datetime(1390, 01, 02)
        jdt_model.save()
        self.assertEqual(
            jDateTimeModel.objects.filter(date_time=datetime.datetime(1390, 01, 02))[0].date_time, jdt_model.date_time
        )

        jdt_model.date_time = jdatetime.date.today()
        jdt_model.save()
        self.assertEqual(
            jDateTimeModel.objects.filter(date_time=jdatetime.date.today())[0].date_time, jdt_model.date_time
        )

        jdt_model.date_time = datetime.date.today()
        jdt_model.save()
        self.assertEqual(
            jDateTimeModel.objects.filter(date_time=datetime.date.today())[0].date_time, jdt_model.date_time
        )

        jdt_model.date_time = datetime.date(1390, 01, 01)
        jdt_model.save()
        self.assertEqual(
            jDateTimeModel.objects.filter(date_time=jdatetime.date(1390, 01, 01))[0].date_time, jdt_model.date_time
        )

        jdt_model.date_time = "1391-01-01 12:12"
        jdt_model.save()
        self.assertEqual(
            jDateTimeModel.objects.filter(date_time=jdatetime.datetime(1391, 01, 01, 12, 12))[0].date_time,
            jdt_model.date_time,
        )

        jdt_model.date_time = "1391-01-01 12:12:12"
        jdt_model.save()
        self.assertEqual(
            jDateTimeModel.objects.filter(date_time=jdatetime.datetime(1391, 01, 01, 12, 12, 12))[0].date_time,
            jdt_model.date_time,
        )

        jdt_model.date_time = "2012-01-01 12:12"
        jdt_model.save()
        # TODO: fixme, I'm broken ! I dunno if I ever should be exist
        # self.assertEqual(jDateTimeModel.objects.filter(date_time=datetime.datetime(2012, 01, 01, 12, 12))[0].date_time, jdt_model.date_time)
        self.assertEqual(
            jDateTimeModel.objects.filter(date_time="2012-01-01 12:12")[0].date_time,
            jdatetime.datetime(1390, 10, 11, 12, 12),
        )

        jdt_model.date_time = "2012-01-01"
        jdt_model.save()
        self.assertEqual(
            jDateTimeModel.objects.filter(date_time="2012-01-01")[0].date_time, jdatetime.datetime(1390, 10, 11)
        )

        jdt_model.date_time = "2012-01-01 12:12:12"
        jdt_model.save()
        self.assertEqual(
            jDateTimeModel.objects.filter(date_time="2012-01-01 12:12:12")[0].date_time,
            jdatetime.datetime(1390, 10, 11, 12, 12, 12),
        )

        jdt_model.date_time = "1391-01-01 12:12:12.2222"
        jdt_model.save()
        self.assertEqual(jDateTimeModel.objects.filter(date_time="1391-01-01 12:12:12.2222")[0], jdt_model)
예제 #59
0
    def test_isoformat_default_args(self):
        jdt = jdatetime.datetime(1398, 4, 11)
        jiso = jdt.isoformat()

        self.assertAlmostEqual(jiso, '1398-04-11T00:00:00')
예제 #60
0
 def test_datetimes_with_different_locales_inequality_works(self):
     dt_en = jdatetime.datetime(2018, 4, 15, 0, 0, 0, locale='en_US')
     dt_fa = jdatetime.datetime(2018, 4, 15, 0, 0, 0, locale='fa_IR')
     self.assertTrue(dt_en != dt_fa)