python类make_aware()的实例源码

test_models.py 文件源码 项目:socialhome 作者: jaywink 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def setUpTestData(cls):
        super().setUpTestData()
        cls.create_local_and_remote_user()
        cls.user2 = AnonymousUser()
        cls.local_user = UserFactory()
        cls.public_content = ContentFactory(
            visibility=Visibility.PUBLIC, text="**Foobar**", author=cls.profile,
        )
        cls.site_content = ContentFactory(
            visibility=Visibility.SITE, text="_Foobar_"
        )
        cls.limited_content = ContentFactory(visibility=Visibility.LIMITED)
        cls.self_content = ContentFactory(visibility=Visibility.SELF)
        cls.remote_content = ContentFactory(
            visibility=Visibility.PUBLIC, remote_created=make_aware(datetime.datetime(2015, 1, 1)),
            author=cls.remote_profile,
        )
        cls.ids = [
            cls.public_content.id, cls.site_content.id, cls.limited_content.id, cls.self_content.id
        ]
        cls.set = {
            cls.public_content, cls.site_content, cls.limited_content, cls.self_content
        }
models.py 文件源码 项目:django_pipedrive 作者: MasAval 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def datetime_from_simple_time(cls, el, datetime_field):
        """
        The function takes a datetime_fieldname and
        returns a datetime aware of the timezone.
        Returns None if fields do not exist in el.
        """
        if (datetime_field not in el or
            el[datetime_field] is None or
            el[datetime_field] == '0000-00-00 00:00:00' or
                el[datetime_field] == ''):

            return None
        else:
            return timezone.make_aware(
                datetime.datetime.strptime(u"{} UTC".format(el[datetime_field]), "%Y-%m-%d %H:%M:%S %Z"),
                pytz.utc)
test_utils.py 文件源码 项目:django-souvenirs 作者: appsembler 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def test_iter_quarters():
    start = timezone.make_aware(datetime(2015, 11, 30, 1, 2, 3))
    end = timezone.make_aware(datetime(2017, 2, 28, 11, 22, 33))

    quarters = iter_quarters(start, end)

    assert type(quarters) is types.GeneratorType

    starts = [
        datetime.combine(datetime(year, month, day).date(), start.timetz())
        for year, month, day in [
                (2015, 11, 30),
                (2016, 2, 29),  # leap!
                (2016, 5, 30),
                (2016, 8, 30),
                (2016, 11, 30),
                (2017, 2, 28),
        ]
    ]

    ends = starts[1:] + [end]

    assert list(quarters) == list(zip(starts, ends))
test_utils.py 文件源码 项目:django-souvenirs 作者: appsembler 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def test_next_month():
    dt = timezone.make_aware(datetime(2017, 3, 30, 11, 5))

    assert next_month(dt) == timezone.make_aware(datetime(2017, 4, 30, 11, 5))
    assert next_month(dt, delta=2) == timezone.make_aware(datetime(2017, 5, 30, 11, 5))
    assert next_month(dt, delta=12) == timezone.make_aware(datetime(2018, 3, 30, 11, 5))
    assert next_month(dt, delta=-1) == timezone.make_aware(datetime(2017, 2, 28, 11, 5))
    assert next_month(dt, delta=-12) == timezone.make_aware(datetime(2016, 3, 30, 11, 5))

    assert (next_month(dt, preferred_dom=31) ==
            timezone.make_aware(datetime(2017, 4, 30, 11, 5)))
    assert (next_month(dt, preferred_dom=31, delta=2)
            == timezone.make_aware(datetime(2017, 5, 31, 11, 5)))
    assert (next_month(dt, preferred_dom=31, delta=12)
            == timezone.make_aware(datetime(2018, 3, 31, 11, 5)))
    assert (next_month(dt, preferred_dom=31, delta=-1)
            == timezone.make_aware(datetime(2017, 2, 28, 11, 5)))
    assert (next_month(dt, preferred_dom=31, delta=-12)
            == timezone.make_aware(datetime(2016, 3, 31, 11, 5)))

    with pytest.raises(ValueError):
        next_month(dt, delta=0)
parse_date.py 文件源码 项目:mos-horizon 作者: Mirantis 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def render(self, datestring):
        """Parses a date-like input string into a timezone aware Python
        datetime.
        """
        formats = ["%Y-%m-%dT%H:%M:%S.%f", "%Y-%m-%d %H:%M:%S.%f",
                   "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S"]
        if datestring:
            for format in formats:
                try:
                    parsed = datetime.strptime(datestring, format)
                    if not timezone.is_aware(parsed):
                        parsed = timezone.make_aware(parsed, timezone.utc)
                    return parsed
                except Exception:
                    pass
        return None
imagemodels.py 文件源码 项目:ecs_sclm 作者: meaningful 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def save(self, *args, **kwargs):
            if self.date_taken is None:
                try:
                    exif_date = self.exif.get('DateTimeOriginal', None)
                    if exif_date is not None:
                        d, t = exif_date.split(" ")
                        year, month, day = d.split(':')
                        hour, minute, second = t.split(':')
                        if getattr(settings, "USE_TZ", False):
                            tz = get_current_timezone()
                            self.date_taken = make_aware(datetime(
                                int(year), int(month), int(day),
                                int(hour), int(minute), int(second)), tz)
                        else:
                            self.date_taken = datetime(
                                int(year), int(month), int(day),
                                int(hour), int(minute), int(second))
                except Exception:
                    pass
            if self.date_taken is None:
                self.date_taken = now()
            super(Image, self).save(*args, **kwargs)
utils.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def from_current_timezone(value):
    """
    When time zone support is enabled, convert naive datetimes
    entered in the current time zone to aware datetimes.
    """
    if settings.USE_TZ and value is not None and timezone.is_naive(value):
        current_timezone = timezone.get_current_timezone()
        try:
            return timezone.make_aware(value, current_timezone)
        except Exception:
            message = _(
                '%(datetime)s couldn\'t be interpreted '
                'in time zone %(current_timezone)s; it '
                'may be ambiguous or it may not exist.'
            )
            params = {'datetime': value, 'current_timezone': current_timezone}
            six.reraise(ValidationError, ValidationError(
                message,
                code='ambiguous_timezone',
                params=params,
            ), sys.exc_info()[2])
    return value
operations.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def year_lookup_bounds_for_datetime_field(self, value):
        """
        Returns a two-elements list with the lower and upper bound to be used
        with a BETWEEN operator to query a DateTimeField value using a year
        lookup.

        `value` is an int, containing the looked-up year.
        """
        first = datetime.datetime(value, 1, 1)
        second = datetime.datetime(value, 12, 31, 23, 59, 59, 999999)
        if settings.USE_TZ:
            tz = timezone.get_current_timezone()
            first = timezone.make_aware(first, tz)
            second = timezone.make_aware(second, tz)
        first = self.adapt_datetimefield_value(first)
        second = self.adapt_datetimefield_value(second)
        return [first, second]
__init__.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def get_prep_value(self, value):
        value = super(DateTimeField, self).get_prep_value(value)
        value = self.to_python(value)
        if value is not None and settings.USE_TZ and timezone.is_naive(value):
            # For backwards compatibility, interpret naive datetimes in local
            # time. This won't work during DST change, but we can't do much
            # about it, so we let the exceptions percolate up the call stack.
            try:
                name = '%s.%s' % (self.model.__name__, self.name)
            except AttributeError:
                name = '(unbound)'
            warnings.warn("DateTimeField %s received a naive datetime (%s)"
                          " while time zone support is active." %
                          (name, value),
                          RuntimeWarning)
            default_timezone = timezone.get_default_timezone()
            value = timezone.make_aware(value, default_timezone)
        return value
utils.py 文件源码 项目:NarshaTech 作者: KimJangHyeon 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def from_current_timezone(value):
    """
    When time zone support is enabled, convert naive datetimes
    entered in the current time zone to aware datetimes.
    """
    if settings.USE_TZ and value is not None and timezone.is_naive(value):
        current_timezone = timezone.get_current_timezone()
        try:
            return timezone.make_aware(value, current_timezone)
        except Exception:
            message = _(
                '%(datetime)s couldn\'t be interpreted '
                'in time zone %(current_timezone)s; it '
                'may be ambiguous or it may not exist.'
            )
            params = {'datetime': value, 'current_timezone': current_timezone}
            six.reraise(ValidationError, ValidationError(
                message,
                code='ambiguous_timezone',
                params=params,
            ), sys.exc_info()[2])
    return value
models.py 文件源码 项目:CoBL-public 作者: lingdb 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def checkTime(self, t):
        """
        Returns true if the given datetime t is
        less then a second different from the current
        lastTouched value.
        """
        if self.lastTouched is None:
            return True

        def make_aware(time):
            if time.tzinfo is None:
                return timezone.make_aware(
                    time, timezone.get_current_timezone())
            return time

        self.lastTouched = make_aware(self.lastTouched)
        t = make_aware(t)
        return abs(t - self.lastTouched).seconds == 0
tests.py 文件源码 项目:Server 作者: malaonline 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def test_parse_date(self):
        self.assertEqual(parse_date('2016-06-1', False), datetime.datetime(2016,6,1))
        self.assertEqual(parse_date('2016-06-1'), timezone.make_aware(datetime.datetime(2016,6,1)))
        self.assertEqual(parse_date('2016-06-18', False), datetime.datetime(2016,6,18))
        self.assertEqual(parse_date('2016-06-18', True), timezone.make_aware(datetime.datetime(2016,6,18)))
        self.assertEqual(parse_date('2016-12-08', False), datetime.datetime(2016,12,8))
        self.assertEqual(parse_date('2016-12-08'), timezone.make_aware(datetime.datetime(2016,12,8)))
        self.assertEqual(parse_date('2016-12-08 4', False), datetime.datetime(2016,12,8,4))
        self.assertEqual(parse_date('2016-12-08 4', True), timezone.make_aware(datetime.datetime(2016,12,8,4)))
        self.assertEqual(parse_date('2016-12-08 23', False), datetime.datetime(2016,12,8,23))
        self.assertEqual(parse_date('2016-12-08 23'), timezone.make_aware(datetime.datetime(2016,12,8,23)))
        self.assertEqual(parse_date('2016-12-08 05:24', False), datetime.datetime(2016,12,8,5,24))
        self.assertEqual(parse_date('2016-12-08 05:24', True), timezone.make_aware(datetime.datetime(2016,12,8,5,24)))
        self.assertEqual(parse_date('2016-12-08 23:09:25', False), datetime.datetime(2016,12,8,23,9,25))
        self.assertEqual(parse_date('2016-12-08 23:09:25'), timezone.make_aware(datetime.datetime(2016,12,8,23,9,25)))
        self.assertEqual(parse_date_next('2016-06-1', False), datetime.datetime(2016,6,2))
        self.assertEqual(parse_date_next('2016-06-18', False), datetime.datetime(2016,6,19))
        self.assertEqual(parse_date_next('2016-12-31', False), datetime.datetime(2017,1,1))
        self.assertEqual(parse_date_next('2016-12-08 4', False), datetime.datetime(2016,12,8,5))
        self.assertEqual(parse_date_next('2016-12-08 23', False), datetime.datetime(2016,12,9,0))
        self.assertEqual(parse_date_next('2016-12-08 05:24', False), datetime.datetime(2016,12,8,5,25))
        self.assertEqual(parse_date_next('2016-12-08 05:59', False), datetime.datetime(2016,12,8,6,0))
        self.assertEqual(parse_date_next('2016-12-08 23:09:25', False), datetime.datetime(2016,12,8,23,9,26))
        self.assertEqual(parse_date_next('2016-12-08 23:09:59', False), datetime.datetime(2016,12,8,23,10,0))
types.py 文件源码 项目:Server 作者: malaonline 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def parse_date_next(s, to_aware=True):
    d = None
    if _re_date.match(s):
        d = datetime.datetime.strptime(s, DATE_P_FORMAT)
        d += datetime.timedelta(days=1)
    if _re_date_h.match(s):
        d = datetime.datetime.strptime(s, DATE_P_FORMAT_WITH_HH)
        d += datetime.timedelta(hours=1)
    if _re_date_h_m.match(s):
        d = datetime.datetime.strptime(s, DATE_P_FORMAT_WITH_HH_MM)
        d += datetime.timedelta(minutes=1)
    if _re_date_full.match(s):
        d = datetime.datetime.strptime(s, DATE_P_FORMAT_FULL)
        d += datetime.timedelta(seconds=1)
    if d is not None and to_aware:
        return make_aware(d)
    return d
views.py 文件源码 项目:Server 作者: malaonline 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def clear_up_time_slot_set(self, time_slot_set: dict, month_start: datetime.datetime, month_end: datetime.datetime):
        # ??time_slot
        # ?????????
        remove_key = []
        for key, val in time_slot_set.items():
            current_time = make_aware(datetime.datetime.strptime(key, MySchoolTimetable.CollectTimeSlot.time_formula))
            if month_start <= current_time <= month_end:
                # ??????????
                time_slot_set[key] = sorted(val, key=lambda item: item["start"])
                # ??datetime
                for one_val in time_slot_set[key]:
                    one_val.pop("start", "")
            else:
                # ?????????
                remove_key.append(key)
        # ???????
        for key in remove_key:
            time_slot_set.pop(key)
external_serializers.py 文件源码 项目:valhalla 作者: LCOGT 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def get_status(self, obj):
        status = 'NOT_ATTEMPTED'
        if self.get_completed(obj):
            return 'COMPLETED'
        if self.get_percent_completed(obj) > 0:
            return 'PARTIALLY-COMPLETED'
        if obj['aborted']:
            return 'ABORTED'
        if self.get_failed(obj):
            return 'FAILED'
        if obj['canceled']:
            return 'CANCELED'
        if not obj['canceled'] and not self.get_failed(obj):
            if timezone.make_aware(parse(obj['end'])) > timezone.now():
                status = 'SCHEDULED'
                if timezone.make_aware(parse(obj['start'])) < timezone.now():
                    status = 'IN_PROGRESS'
        return status
utils.py 文件源码 项目:Scrum 作者: prakharchoudhary 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def from_current_timezone(value):
    """
    When time zone support is enabled, convert naive datetimes
    entered in the current time zone to aware datetimes.
    """
    if settings.USE_TZ and value is not None and timezone.is_naive(value):
        current_timezone = timezone.get_current_timezone()
        try:
            return timezone.make_aware(value, current_timezone)
        except Exception:
            message = _(
                '%(datetime)s couldn\'t be interpreted '
                'in time zone %(current_timezone)s; it '
                'may be ambiguous or it may not exist.'
            )
            params = {'datetime': value, 'current_timezone': current_timezone}
            six.reraise(ValidationError, ValidationError(
                message,
                code='ambiguous_timezone',
                params=params,
            ), sys.exc_info()[2])
    return value
test_usage_logging.py 文件源码 项目:lighthouse 作者: dstl 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def test_update_usage_within_one_hour(self):
        self.assertEquals(self.link.usage_total(), 0)
        self.assertEquals(self.other_link.usage_total(), 0)

        with mock.patch('django.utils.timezone.now') as mock_now:
            mock_now.return_value = make_aware(datetime(2016, 3, 1, 10, 0, 0))
            self.link.register_usage(self.user)

            mock_now.return_value = make_aware(datetime(2016, 3, 1, 10, 59, 0))
            self.link.register_usage(self.user)

            self.assertEquals(self.link.usage_today(), 1)
            self.assertEquals(self.link.usage_total(), 1)
            self.assertEquals(self.other_link.usage_total(), 0)

        usage = self.link.usage.all()[0]
        self.assertEquals(usage.duration, 3540)
test_usage_logging.py 文件源码 项目:lighthouse 作者: dstl 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def test_create_new_usage_after_one_hour(self):
        self.assertEquals(self.link.usage_total(), 0)
        self.assertEquals(self.other_link.usage_total(), 0)

        with mock.patch('django.utils.timezone.now') as mock_now:
            mock_now.return_value = make_aware(datetime(2016, 3, 1, 10, 0, 0))
            self.link.register_usage(self.user)

            mock_now.return_value = make_aware(datetime(2016, 3, 1, 11, 0, 0))
            self.link.register_usage(self.user)

            self.assertEquals(self.link.usage_today(), 2)
            self.assertEquals(self.link.usage_total(), 2)
            self.assertEquals(self.other_link.usage_total(), 0)

        usage = self.link.usage.all()
        self.assertEquals(usage[0].duration, 0)
        self.assertEquals(usage[1].duration, 0)
test_usage_logging.py 文件源码 项目:lighthouse 作者: dstl 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def test_usage_this_week(self):
        self.assertEquals(self.link.usage_total(), 0)
        self.assertEquals(self.other_link.usage_total(), 0)

        with mock.patch('django.utils.timezone.now') as mock_now:
            # register usage on a specific Tuesday
            mock_now.return_value = make_aware(datetime(2016, 3, 1, 10, 0, 0))
            self.link.register_usage(self.user)

            # test this counts as "this week" on the following Thursday
            mock_now.return_value = make_aware(datetime(2016, 3, 3, 12, 0, 0))

            self.assertEquals(self.link.usage_today(), 0)
            self.assertEquals(self.link.usage_this_week(), 1)
            self.assertEquals(self.link.usage_past_seven_days(), 1)
            self.assertEquals(self.link.usage_past_thirty_days(), 1)
            self.assertEquals(self.link.usage_total(), 1)
            self.assertEquals(self.other_link.usage_total(), 0)
test_usage_logging.py 文件源码 项目:lighthouse 作者: dstl 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def test_usage_this_month(self):
        self.assertEquals(self.link.usage_total(), 0)
        self.assertEquals(self.other_link.usage_total(), 0)

        with mock.patch('django.utils.timezone.now') as mock_now:
            # register usage in a specific month
            mock_now.return_value = make_aware(datetime(2016, 2, 29, 10, 0, 0))
            self.link.register_usage(self.user)

            # register usage in the next month
            mock_now.return_value = make_aware(datetime(2016, 3, 1, 10, 0, 0))
            self.link.register_usage(self.user)

            # test it from the point of view of the specific month
            mock_now.return_value = make_aware(datetime(2016, 3, 3, 12, 0, 0))

            self.assertEquals(self.link.usage_today(), 0)
            self.assertEquals(self.link.usage_this_week(), 2)
            self.assertEquals(self.link.usage_past_seven_days(), 2)
            self.assertEquals(self.link.usage_past_thirty_days(), 2)
            self.assertEquals(self.link.usage_this_month(), 1)
            self.assertEquals(self.link.usage_total(), 2)
            self.assertEquals(self.other_link.usage_total(), 0)
utils.py 文件源码 项目:django 作者: alexsukhrin 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def from_current_timezone(value):
    """
    When time zone support is enabled, convert naive datetimes
    entered in the current time zone to aware datetimes.
    """
    if settings.USE_TZ and value is not None and timezone.is_naive(value):
        current_timezone = timezone.get_current_timezone()
        try:
            return timezone.make_aware(value, current_timezone)
        except Exception:
            message = _(
                '%(datetime)s couldn\'t be interpreted '
                'in time zone %(current_timezone)s; it '
                'may be ambiguous or it may not exist.'
            )
            params = {'datetime': value, 'current_timezone': current_timezone}
            six.reraise(ValidationError, ValidationError(
                message,
                code='ambiguous_timezone',
                params=params,
            ), sys.exc_info()[2])
    return value
pybase.py 文件源码 项目:python-ibmdb-django 作者: ibmdb 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def _format_parameters( self, parameters ):
        parameters = list( parameters )
        for index in range( len( parameters ) ):
            # With raw SQL queries, datetimes can reach this function
            # without being converted by DateTimeField.get_db_prep_value.
            if settings.USE_TZ and isinstance( parameters[index], datetime.datetime ):
                param = parameters[index]
                if timezone.is_naive( param ):
                    warnings.warn(u"Received a naive datetime (%s)"
                              u" while time zone support is active." % param,
                              RuntimeWarning)
                    default_timezone = timezone.get_default_timezone()
                    param = timezone.make_aware( param, default_timezone )
                param = param.astimezone(timezone.utc).replace(tzinfo=None)
                parameters[index] = param
        return tuple( parameters )

    # Over-riding this method to modify SQLs which contains format parameter to qmark.
fields.py 文件源码 项目:kolibri 作者: learningequality 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def create_timezonestamp(value):
    if value.tzinfo and hasattr(value.tzinfo, 'zone'):
        # We have a pytz timezone, we can work with this
        tz = value.tzinfo.zone
    elif value.tzinfo:
        # Got some timezone data, but it's not a pytz timezone
        # Let's just assume someone used dateutil parser on a UTC
        # ISO format timestamp
        # Fixes https://github.com/learningequality/kolibri/issues/1824
        tz = pytz.utc
        value = value.astimezone(tz)
    else:
        tz = timezone.get_current_timezone().zone
        value = timezone.make_aware(value, timezone.get_current_timezone())
    date_time_string = value.astimezone(pytz.utc).strftime(date_time_format)
    tz_string = tz_format.format(tz=tz)
    value = db_storage_string.format(date_time_string=date_time_string, tz_string=tz_string)
    return value
utils.py 文件源码 项目:Gypsy 作者: benticarlos 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def from_current_timezone(value):
    """
    When time zone support is enabled, convert naive datetimes
    entered in the current time zone to aware datetimes.
    """
    if settings.USE_TZ and value is not None and timezone.is_naive(value):
        current_timezone = timezone.get_current_timezone()
        try:
            return timezone.make_aware(value, current_timezone)
        except Exception:
            message = _(
                '%(datetime)s couldn\'t be interpreted '
                'in time zone %(current_timezone)s; it '
                'may be ambiguous or it may not exist.'
            )
            params = {'datetime': value, 'current_timezone': current_timezone}
            six.reraise(ValidationError, ValidationError(
                message,
                code='ambiguous_timezone',
                params=params,
            ), sys.exc_info()[2])
    return value
models.py 文件源码 项目:guifiadmin 作者: guifi-org 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def create_invoices(self, date):
        # monthly quotas
        start = make_aware(datetime.datetime(date.year, date.month, 1), utc)
        if date.month == 12:
            year = date.year + 1
            month = 1
        else:
            year = date.year
            month = date.month + 1
        end = make_aware(datetime.datetime(year, month, 1), utc)
        for quota in self.filter(quota_type__periodicity=QuotaType.MONTHLY):
            if not quota.quotainvoice_set.filter(date__range=(start, end)).exists():
                print "quota necesita invoice:", quota.create_invoice(date)

        # yearly quotas
        start = make_aware(datetime.datetime(date.year, 1, 1), utc)
        end = make_aware(datetime.datetime(date.year + 1, 1, 1), utc)

        quotainvoices = []
        for quota in self.filter(quota_type__periodicity=QuotaType.ANUAL):
            if not quota.quotainvoice_set.filter(date__range=(start, end)).exists():
                quotainvoice = quota.create_invoice(date)
                quotainvoices.append(quotainvoice)
        return quotainvoices
admin.py 文件源码 项目:guifiadmin 作者: guifi-org 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def needs_invoice(self, obj):
        if obj.last_invoice_date is None:
            return True
        date = now()
        if obj.quota_type.periodicity == obj.quota_type.ANUAL:
            start = make_aware(datetime.datetime(date.year, 1, 1), utc)
            return obj.last_invoice_date < start
        elif obj.quota_type.periodicity == obj.quota_type.ANUAL:
            if date.month == 12:
                year = date.year + 1
                month = 1
            else:
                year = date.year
                month = date.month + 1
            start = make_aware(datetime.datetime(year, month, 1), utc)
            return obj.last_invoice_date < start
        return False
utils.py 文件源码 项目:DjangoBlog 作者: 0daybug 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def from_current_timezone(value):
    """
    When time zone support is enabled, convert naive datetimes
    entered in the current time zone to aware datetimes.
    """
    if settings.USE_TZ and value is not None and timezone.is_naive(value):
        current_timezone = timezone.get_current_timezone()
        try:
            return timezone.make_aware(value, current_timezone)
        except Exception:
            message = _(
                '%(datetime)s couldn\'t be interpreted '
                'in time zone %(current_timezone)s; it '
                'may be ambiguous or it may not exist.'
            )
            params = {'datetime': value, 'current_timezone': current_timezone}
            six.reraise(ValidationError, ValidationError(
                message,
                code='ambiguous_timezone',
                params=params,
            ), sys.exc_info()[2])
    return value
base.py 文件源码 项目:DjangoBlog 作者: 0daybug 项目源码 文件源码 阅读 49 收藏 0 点赞 0 评论 0
def adapt_datetime_with_timezone_support(value, conv):
    # Equivalent to DateTimeField.get_db_prep_value. Used only by raw SQL.
    if settings.USE_TZ:
        if timezone.is_naive(value):
            warnings.warn("MySQL received a naive datetime (%s)"
                          " while time zone support is active." % value,
                          RuntimeWarning)
            default_timezone = timezone.get_default_timezone()
            value = timezone.make_aware(value, default_timezone)
        value = value.astimezone(timezone.utc).replace(tzinfo=None)
    return Thing2Literal(value.strftime("%Y-%m-%d %H:%M:%S.%f"), conv)

# MySQLdb-1.2.1 returns TIME columns as timedelta -- they are more like
# timedelta in terms of actual behavior as they are signed and include days --
# and Django expects time, so we still need to override that. We also need to
# add special handling for SafeText and SafeBytes as MySQLdb's type
# checking is too tight to catch those (see Django ticket #6052).
# Finally, MySQLdb always returns naive datetime objects. However, when
# timezone support is active, Django expects timezone-aware datetime objects.
sync_deleted_instances_fix.py 文件源码 项目:fieldsight-kobocat 作者: awemulya 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def handle(self, *args, **kwargs):
        # Reset all sql deletes to None
        Instance.objects.exclude(
            deleted_at=None, xform__downloadable=True).update(deleted_at=None)

        # Get all mongo deletes
        query = '{"$and": [{"_deleted_at": {"$exists": true}}, ' \
                '{"_deleted_at": {"$ne": null}}]}'
        query = json.loads(query)
        xform_instances = settings.MONGO_DB.instances
        cursor = xform_instances.find(query)
        for record in cursor:
            # update sql instance with deleted_at datetime from mongo
            try:
                i = Instance.objects.get(
                    uuid=record["_uuid"],  xform__downloadable=True)
            except Instance.DoesNotExist:
                continue
            else:
                deleted_at = parse_datetime(record["_deleted_at"])
                if not timezone.is_aware(deleted_at):
                    deleted_at = timezone.make_aware(
                        deleted_at, timezone.utc)
                i.set_deleted(deleted_at)
models.py 文件源码 项目:ecs 作者: ecs-org 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def timetable_entries_which_violate_constraints(self):
        start_date = self.start.date()
        entries_which_violate_constraints = []
        for constraint in self.constraints.all():
            constraint_start = timezone.make_aware(
                datetime.combine(start_date, constraint.start_time),
                timezone.get_current_timezone())
            constraint_end = timezone.make_aware(
                datetime.combine(start_date, constraint.end_time),
                timezone.get_current_timezone())
            participations = Participation.objects.filter(entry__meeting=self,
                user=constraint.user, ignored_for_optimization=False,
                entry__timetable_index__isnull=False)
            for participation in participations:
                start = participation.entry.start
                end = participation.entry.end
                if (constraint_start >= start and constraint_start < end) or \
                    (constraint_end > start and constraint_end <= end) or \
                    (constraint_start <= start and constraint_end >= end):
                    entries_which_violate_constraints.append(participation.entry)
        return entries_which_violate_constraints


问题


面经


文章

微信
公众号

扫码关注公众号