python类get_default_timezone()的实例源码

utils.py 文件源码 项目:django-celery-monitor 作者: jezdez 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def correct_awareness(value):
    """Fix the given datetime timezone awareness."""
    if isinstance(value, datetime):
        if settings.USE_TZ:
            return make_aware(value)
        elif timezone.is_aware(value):
            default_tz = timezone.get_default_timezone()
            return timezone.make_naive(value, default_tz)
    return value
django_rq.py 文件源码 项目:DCRM 作者: 82Flex 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def to_localtime(time):
    '''
        A function to convert naive datetime to
        localtime base on settings
    '''
    utc_time = time.replace(tzinfo=timezone.utc)
    to_zone = timezone.get_default_timezone()
    return utc_time.astimezone(to_zone)
storage.py 文件源码 项目:django 作者: alexsukhrin 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def _possibly_make_aware(dt):
    """
    Convert a datetime object in the local timezone to aware
    in UTC, if USE_TZ is True.
    """
    # This function is only needed to help with the deprecations above and can
    # be removed in Django 2.0, RemovedInDjango20Warning.
    if settings.USE_TZ:
        tz = timezone.get_default_timezone()
        return timezone.make_aware(dt, tz).astimezone(timezone.utc)
    else:
        return dt
fields.py 文件源码 项目:sdining 作者: Lurance 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def default_timezone(self):
        return timezone.get_default_timezone() if settings.USE_TZ else None
views.py 文件源码 项目:wagtail_room_booking 作者: Tamriel 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def get_context_data(self, request, **kwargs):
        context = super(CalendarByPeriodsView, self).get_context_data(**kwargs)
        calendar = self.object
        periods = kwargs.get('periods', None)
        try:
            date = coerce_date_dict(request.GET)
        except ValueError:
            raise Http404
        if date:
            try:
                date = datetime.datetime(**date)
            except ValueError:
                raise Http404
        else:
            date = timezone.now()
        event_list = GET_EVENTS_FUNC(request, calendar)

        if 'django_timezone' in self.request.session:
            local_timezone = pytz.timezone(request.session['django_timezone'])
        else:
            local_timezone = timezone.get_default_timezone()
        period_objects = {}
        for period in periods:
            if period.__name__.lower() == 'year':
                period_objects[period.__name__.lower()] = period(event_list, date, None, local_timezone)
            else:
                period_objects[period.__name__.lower()] = period(event_list, date, None, None, local_timezone)

        context.update({
            'date': date,
            'periods': period_objects,
            'calendar': calendar,
            'weekday_names': weekday_names,
            'here': quote(request.get_full_path()),
        })
        return context
tablefilter.py 文件源码 项目:isar 作者: ilbers 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def dateStringsToQ(self, field_name, date_from_str, date_to_str):
        """
        Convert the date strings from_date_str and to_date_str into a
        set of args in the form

          {'<field_name>__gte': <date from>, '<field_name>__lte': <date to>}

        where date_from and date_to are Django-timezone-aware dates; then
        convert that into a Django Q object

        Returns the Q object based on those criteria
        """

        # one of the values required for the filter is missing, so set
        # it to the one which was supplied
        if date_from_str == '':
            date_from_str = date_to_str
        elif date_to_str == '':
            date_to_str = date_from_str

        date_from_naive = dateparse.parse_datetime(date_from_str + ' 00:00:00')
        date_to_naive = dateparse.parse_datetime(date_to_str + ' 23:59:59')

        tz = timezone.get_default_timezone()
        date_from = timezone.make_aware(date_from_naive, tz)
        date_to = timezone.make_aware(date_to_naive, tz)

        args = {}
        args[field_name + '__gte'] = date_from
        args[field_name + '__lte'] = date_to

        return Q(**args)
storage.py 文件源码 项目:Gypsy 作者: benticarlos 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def _possibly_make_aware(dt):
    """
    Convert a datetime object in the local timezone to aware
    in UTC, if USE_TZ is True.
    """
    # This function is only needed to help with the deprecations above and can
    # be removed in Django 2.0, RemovedInDjango20Warning.
    if settings.USE_TZ:
        tz = timezone.get_default_timezone()
        return timezone.make_aware(dt, tz).astimezone(timezone.utc)
    else:
        return dt
base.py 文件源码 项目:DjangoBlog 作者: 0daybug 项目源码 文件源码 阅读 37 收藏 0 点赞 0 评论 0
def adapt_datetime_with_timezone_support(value):
    # Equivalent to DateTimeField.get_db_prep_value. Used only by raw SQL.
    if settings.USE_TZ:
        if timezone.is_naive(value):
            warnings.warn("SQLite 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 value.isoformat(str(" "))
fields.py 文件源码 项目:jianshu-api 作者: strugglingyouth 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def default_timezone(self):
        return timezone.get_default_timezone() if settings.USE_TZ else None
base.py 文件源码 项目:trydjango18 作者: wei0104 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def adapt_datetime_with_timezone_support(value):
    # Equivalent to DateTimeField.get_db_prep_value. Used only by raw SQL.
    if settings.USE_TZ:
        if timezone.is_naive(value):
            warnings.warn("SQLite 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 value.isoformat(str(" "))
fields.py 文件源码 项目:esdc-ce 作者: erigones 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def from_native(self, value):
        if value in validators.EMPTY_VALUES:
            return None

        if isinstance(value, datetime.datetime):
            if timezone and settings.USE_TZ and timezone.is_aware(value):
                # Convert aware datetimes to the default time zone
                # before casting them to dates (#17742).
                default_timezone = timezone.get_default_timezone()
                value = timezone.make_naive(value, default_timezone)
            return value.date()
        if isinstance(value, datetime.date):
            return value

        for fmt in self.input_formats:
            if fmt.lower() == ISO_8601:
                try:
                    parsed = parse_date(value)
                except (ValueError, TypeError):
                    pass
                else:
                    if parsed is not None:
                        return parsed
            else:
                try:
                    parsed = datetime.datetime.strptime(value, fmt)
                except (ValueError, TypeError):
                    pass
                else:
                    return parsed.date()

        msg = self.error_messages['invalid'] % readable_date_formats(self.input_formats)

        raise ValidationError(msg)
fields.py 文件源码 项目:esdc-ce 作者: erigones 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def from_native(self, value):
        if value in validators.EMPTY_VALUES:
            return None

        if isinstance(value, datetime.datetime):
            return value
        if isinstance(value, datetime.date):
            value = datetime.datetime(value.year, value.month, value.day)
            if settings.USE_TZ:
                # 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.
                warnings.warn("DateTimeField 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)
            return value

        for fmt in self.input_formats:
            if fmt.lower() == ISO_8601:
                try:
                    parsed = parse_datetime(value)
                except (ValueError, TypeError):
                    pass
                else:
                    if parsed is not None:
                        return parsed
            else:
                try:
                    parsed = datetime.datetime.strptime(value, fmt)
                except (ValueError, TypeError):
                    pass
                else:
                    return parsed

        msg = self.error_messages['invalid'] % readable_datetime_formats(self.input_formats)

        raise ValidationError(msg)
register_view.py 文件源码 项目:esdc-ce 作者: erigones 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def _pre_save_callback(self, user, upform, *args, **kwargs):
        """
        Stuff that needs to be done pre-saving the user object.
        """
        # Just to be sure - for a never logged-in user this should be True:
        # user.last_login <= user.date_joined
        user.last_login = timezone.datetime(1970, 1, 1, 0, 0, 0, 0, timezone.get_default_timezone())
        # Update username to email for common users
        user.username = user.email.lower()
        # Update user default datacenter
        user.default_dc = self.request.dc

        return user, upform

    # noinspection PyUnusedLocal
storage.py 文件源码 项目:ims 作者: ims-team 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def _possibly_make_aware(dt):
    """
    Convert a datetime object in the local timezone to aware
    in UTC, if USE_TZ is True.
    """
    # This function is only needed to help with the deprecations above and can
    # be removed in Django 2.0, RemovedInDjango20Warning.
    if settings.USE_TZ:
        tz = timezone.get_default_timezone()
        return timezone.make_aware(dt, tz).astimezone(timezone.utc)
    else:
        return dt
storage.py 文件源码 项目:lifesoundtrack 作者: MTG 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def _possibly_make_aware(dt):
    """
    Convert a datetime object in the local timezone to aware
    in UTC, if USE_TZ is True.
    """
    # This function is only needed to help with the deprecations above and can
    # be removed in Django 2.0, RemovedInDjango20Warning.
    if settings.USE_TZ:
        tz = timezone.get_default_timezone()
        return timezone.make_aware(dt, tz).astimezone(timezone.utc)
    else:
        return dt
__init__.py 文件源码 项目:lifesoundtrack 作者: MTG 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def to_python(self, value):
        if value is None:
            return value
        if isinstance(value, datetime.datetime):
            if settings.USE_TZ and timezone.is_aware(value):
                # Convert aware datetimes to the default time zone
                # before casting them to dates (#17742).
                default_timezone = timezone.get_default_timezone()
                value = timezone.make_naive(value, default_timezone)
            return value.date()
        if isinstance(value, datetime.date):
            return value

        try:
            parsed = parse_date(value)
            if parsed is not None:
                return parsed
        except ValueError:
            raise exceptions.ValidationError(
                self.error_messages['invalid_date'],
                code='invalid_date',
                params={'value': value},
            )

        raise exceptions.ValidationError(
            self.error_messages['invalid'],
            code='invalid',
            params={'value': value},
        )
dateformat.py 文件源码 项目:lifesoundtrack 作者: MTG 项目源码 文件源码 阅读 48 收藏 0 点赞 0 评论 0
def __init__(self, obj):
        self.data = obj
        self.timezone = None

        # We only support timezone when formatting datetime objects,
        # not date objects (timezone information not appropriate),
        # or time objects (against established django policy).
        if isinstance(obj, datetime.datetime):
            if is_naive(obj):
                self.timezone = get_default_timezone()
            else:
                self.timezone = obj.tzinfo
dateformat.py 文件源码 项目:lifesoundtrack 作者: MTG 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def I(self):
        "'1' if Daylight Savings Time, '0' otherwise."
        try:
            if self.timezone and self.timezone.dst(self.data):
                return '1'
            else:
                return '0'
        except Exception:
            # pytz raises AmbiguousTimeError during the autumn DST change.
            # This happens mainly when __init__ receives a naive datetime
            # and sets self.timezone = get_default_timezone().
            return ''
storage.py 文件源码 项目:django-open-lecture 作者: DmLitov4 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def _possibly_make_aware(dt):
    """
    Convert a datetime object in the local timezone to aware
    in UTC, if USE_TZ is True.
    """
    # This function is only needed to help with the deprecations above and can
    # be removed in Django 2.0, RemovedInDjango20Warning.
    if settings.USE_TZ:
        tz = timezone.get_default_timezone()
        return timezone.make_aware(dt, tz).astimezone(timezone.utc)
    else:
        return dt
mixins.py 文件源码 项目:LIMS-Backend 作者: LeafLIMS 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def history(self, request, pk=None):
        instance = self.get_object()
        user = request.query_params.get('user', None)  # Default to all users
        start = request.query_params.get('start', None)  # In YYYY-MM-DD format
        if start:
            start = datetime.datetime.strptime(start, '%Y-%m-%d')
        else:
            start = datetime.datetime.min
        start = timezone.make_aware(start, timezone.get_default_timezone())
        end = request.query_params.get('end', None)  # In YYYY-MM-DD format
        if end:
            end = datetime.datetime.strptime(start, '%Y-%m-%d')
        else:
            end = datetime.datetime.today()
        end = timezone.make_aware(end, timezone.get_default_timezone())
        history = []
        for v, version in enumerate(Version.objects.get_for_object(instance).reverse()):
            if (user is not None and version.revision.user.username != user) \
                    or version.revision.date_created < start \
                    or version.revision.date_created > end:
                continue
            history.append({'version': v,
                            'created': version.revision.date_created.strftime('%Y-%m-%d %H:%M:%S'),
                            'user': version.revision.user.username,
                            'data': version.field_dict})
        return Response(history, status=200)


问题


面经


文章

微信
公众号

扫码关注公众号