Python django.utils.timezone 模块,make_aware() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.utils.timezone.make_aware()

项目:socialhome    作者:jaywink    | 项目源码 | 文件源码
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
        }
项目:django_pipedrive    作者:MasAval    | 项目源码 | 文件源码
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)
项目:django-souvenirs    作者:appsembler    | 项目源码 | 文件源码
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))
项目:django-souvenirs    作者:appsembler    | 项目源码 | 文件源码
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)
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
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
项目:ecs_sclm    作者:meaningful    | 项目源码 | 文件源码
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)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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]
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
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
项目:CoBL-public    作者:lingdb    | 项目源码 | 文件源码
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
项目:Server    作者:malaonline    | 项目源码 | 文件源码
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))
项目:Server    作者:malaonline    | 项目源码 | 文件源码
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
项目:Server    作者:malaonline    | 项目源码 | 文件源码
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)
项目:valhalla    作者:LCOGT    | 项目源码 | 文件源码
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
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
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
项目:lighthouse    作者:dstl    | 项目源码 | 文件源码
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)
项目:lighthouse    作者:dstl    | 项目源码 | 文件源码
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)
项目:lighthouse    作者:dstl    | 项目源码 | 文件源码
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)
项目:lighthouse    作者:dstl    | 项目源码 | 文件源码
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)
项目:django    作者:alexsukhrin    | 项目源码 | 文件源码
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
项目:python-ibmdb-django    作者:ibmdb    | 项目源码 | 文件源码
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.
项目:kolibri    作者:learningequality    | 项目源码 | 文件源码
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
项目:Gypsy    作者:benticarlos    | 项目源码 | 文件源码
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
项目:guifiadmin    作者:guifi-org    | 项目源码 | 文件源码
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
项目:guifiadmin    作者:guifi-org    | 项目源码 | 文件源码
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
项目:DjangoBlog    作者:0daybug    | 项目源码 | 文件源码
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
项目:DjangoBlog    作者:0daybug    | 项目源码 | 文件源码
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.
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
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)
项目:ecs    作者:ecs-org    | 项目源码 | 文件源码
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
项目:wanblog    作者:wanzifa    | 项目源码 | 文件源码
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
项目:tabmaster    作者:NicolasMinghetti    | 项目源码 | 文件源码
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
项目:trydjango18    作者:lucifer-yqh    | 项目源码 | 文件源码
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
项目:trydjango18    作者:lucifer-yqh    | 项目源码 | 文件源码
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.
项目:trydjango18    作者:wei0104    | 项目源码 | 文件源码
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
项目:trydjango18    作者:wei0104    | 项目源码 | 文件源码
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.
项目:Silver-Screen    作者:bfbachmann    | 项目源码 | 文件源码
def test_fill_with_duplicate_status(self):
        sample_user=twitter.User(
                id=718443,
                name='Bob Loblaw',
                screen_name='bobby',
                location='Vancouver, Canada',
                verified=True
            )
        sample_status=twitter.Status(
                created_at=datetime.strftime(timezone.make_aware(datetime.now()), '%a %b %d %H:%M:%S +0000 %Y'),
                id=1234567,
                text='Hello world, again!',
                user=sample_user,
                retweet_count=1,
                favorite_count=5,
            )
        movie = Movie.objects.get(imdbID="123456")
        duplicate_tweet = Tweet().fillWithStatusObject(sample_status, movie)

        self.assertEqual(duplicate_tweet.text, 'Hello world')
项目:ims    作者:ims-team    | 项目源码 | 文件源码
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
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
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
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def convert_value(self, value, expression, connection, context):
        if isinstance(self.output_field, DateTimeField):
            if settings.USE_TZ:
                if value is None:
                    raise ValueError(
                        "Database returned an invalid datetime value. "
                        "Are time zone definitions for your database and pytz installed?"
                    )
                value = value.replace(tzinfo=None)
                value = timezone.make_aware(value, self.tzinfo)
        elif isinstance(value, datetime):
            if isinstance(self.output_field, DateField):
                value = value.date()
            elif isinstance(self.output_field, TimeField):
                value = value.time()
        return value
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
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
项目:gentry    作者:akx    | 项目源码 | 文件源码
def store_event(request, project):
    try:
        auth_header = validate_auth_header(request, project)
    except InvalidAuth as ia:
        return JsonResponse({'error': str(ia)}, status=401)

    body = request.body
    if request.META.get('HTTP_CONTENT_ENCODING') == 'deflate':
        body = zlib.decompress(body)

    elif auth_header.get('sentry_version') == '5':  # Support older versions of Raven
        body = zlib.decompress(base64.b64decode(body)).decode('utf8')

    body = json.loads(force_text(body))
    timestamp = make_aware(datetime.fromtimestamp(float(auth_header['sentry_timestamp'])), timezone=UTC)
    with transaction.atomic():
        event = Event.objects.create_from_raven(project_id=project, body=body, timestamp=timestamp)
    try:
        event_received.send(sender=event)
    except:  # pragma: no cover
        logger.warning('event_received signal handling failed', exc_info=True)
        if settings.DEBUG:
            raise
    return JsonResponse({'id': event.id}, status=201)
项目:django-open-lecture    作者:DmLitov4    | 项目源码 | 文件源码
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
项目:LIMS-Backend    作者:LeafLIMS    | 项目源码 | 文件源码
def test_presets(self):
        self.assertIs(EquipmentReservation.objects.filter(id=self._joeReservation.id).exists(),
                      True)
        res1 = EquipmentReservation.objects.get(id=self._joeReservation.id)
        self.assertEqual(res1.start, timezone.make_aware(datetime.datetime(2050, 3, 11)))
        self.assertEqual(res1.end, timezone.make_aware(datetime.datetime(2050, 3, 13)))
        self.assertEqual(res1.reserved_for, "An experiment I'm doing")
        self.assertEqual(res1.reserved_by, self._joeBloggs)
        self.assertEqual(res1.equipment_reserved, self._equipmentSequencer)
        self.assertEqual(res1.is_confirmed, False)
        self.assertEqual(res1.checked_in, False)
        res1 = EquipmentReservation.objects.get(id=self._janeReservation.id)
        self.assertEqual(res1.start, timezone.make_aware(datetime.datetime(2050, 3, 14)))
        self.assertEqual(res1.end, timezone.make_aware(datetime.datetime(2050, 3, 16)))
        self.assertEqual(res1.reserved_for, "Very important sequencing stuff")
        self.assertEqual(res1.reserved_by, self._janeDoe)
        self.assertEqual(res1.equipment_reserved, self._equipmentSequencer)
        self.assertEqual(res1.is_confirmed, False)
        self.assertEqual(res1.checked_in, False)
项目:LIMS-Backend    作者:LeafLIMS    | 项目源码 | 文件源码
def test_staff_create_autoconfirm(self):
        self._asStaff()
        new_res = {"start": timezone.make_aware(datetime.datetime(2050, 6, 14)),
                   "end": timezone.make_aware(datetime.datetime(2050, 6, 16)),
                   "reserved_for": "Something or other I might want to do",
                   "reserved_by": self._staffUser.username,
                   "equipment_reserved": self._equipmentSequencer.name,
                   "is_confirmed": False,
                   "checked_in": False}
        response = self._client.post("/equipmentreservation/", new_res, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertIs(EquipmentReservation.objects.filter(
            reserved_for="Something or other I might want to do").exists(), True)
        res1 = EquipmentReservation.objects.get(
            reserved_for="Something or other I might want to do")
        self.assertEqual(res1.is_confirmed, True)
        self.assertEqual(res1.confirmed_by, self._staffUser)
项目:travlr    作者:gauravkulkarni96    | 项目源码 | 文件源码
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
项目:gougo    作者:amaozhao    | 项目源码 | 文件源码
def get_modified_time(storage, name):
    """
    Get modified time from storage, ensuring the result is a timezone-aware
    datetime.
    """
    try:
        modified_time = storage.modified_time(name)
    except OSError:
        return 0
    except NotImplementedError:
        return None
    if modified_time and timezone.is_naive(modified_time):
        if getattr(settings, 'USE_TZ', False):
            default_timezone = timezone.get_default_timezone()
            return timezone.make_aware(modified_time, default_timezone)
    return modified_time
项目:gougo    作者:amaozhao    | 项目源码 | 文件源码
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)
项目:logo-gen    作者:jellene4eva    | 项目源码 | 文件源码
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
项目:liberator    作者:libscie    | 项目源码 | 文件源码
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