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

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

项目:django-souvenirs    作者:appsembler    | 项目源码 | 文件源码
def setup(self, db, mocker):
        self.tzinfo = timezone.get_current_timezone()
        self.subscription_start = datetime(
            year=2010, month=1, day=24, hour=22, tzinfo=self.tzinfo)
        self.souvenirs = [
            SouvenirFactory(when=datetime(year=i, month=2, day=14,
                                          hour=12, tzinfo=self.tzinfo))
            for i in range(2010, 2018)
        ]
        self.souvenirs.append(
            SouvenirFactory(when=datetime(year=2015, month=10, day=17,
                                          hour=12, tzinfo=self.tzinfo))
        )
        mocked_now = mocker.patch('souvenirs.reports.timezone.now')
        mocked_now.return_value = self.now = datetime(
            year=2017, month=4, day=4, hour=16, tzinfo=self.tzinfo)
项目:django-souvenirs    作者:appsembler    | 项目源码 | 文件源码
def setup(self, db, mocker):
        self.tzinfo = timezone.get_current_timezone()
        self.subscription_start = datetime(
            year=2010, month=1, day=24, hour=22, tzinfo=self.tzinfo)
        self.souvenirs = [
            SouvenirFactory(when=datetime(
                year=i, month=2, day=14, hour=12, tzinfo=self.tzinfo))
            for i in range(2010, 2018)
        ]
        self.souvenirs.append(
            SouvenirFactory(when=datetime(year=2015, month=10, day=17,
                                          hour=12, tzinfo=self.tzinfo))
        )
        mocked_now = mocker.patch('souvenirs.reports.timezone.now')
        mocked_now.return_value = self.now = datetime(
            year=2017, month=4, day=3, hour=23, tzinfo=self.tzinfo)
项目: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 datetimes(self, field_name, kind, order='ASC', tzinfo=None):
        """
        Returns a list of datetime objects representing all available
        datetimes for the given field_name, scoped to 'kind'.
        """
        assert kind in ("year", "month", "day", "hour", "minute", "second"), \
            "'kind' must be one of 'year', 'month', 'day', 'hour', 'minute' or 'second'."
        assert order in ('ASC', 'DESC'), \
            "'order' must be either 'ASC' or 'DESC'."
        if settings.USE_TZ:
            if tzinfo is None:
                tzinfo = timezone.get_current_timezone()
        else:
            tzinfo = None
        return self.annotate(
            datetimefield=DateTime(field_name, kind, tzinfo),
            plain_field=F(field_name)
        ).values_list(
            'datetimefield', flat=True
        ).distinct().filter(plain_field__isnull=False).order_by(('-' if order == 'DESC' else '') + 'datetimefield')
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def get_current_timezone_tag(parser, token):
    """
    Stores the name of the current time zone in the context.

    Usage::

        {% get_current_timezone as TIME_ZONE %}

    This will fetch the currently active time zone and put its name
    into the ``TIME_ZONE`` context variable.
    """
    # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
    args = token.contents.split()
    if len(args) != 3 or args[1] != 'as':
        raise TemplateSyntaxError("'get_current_timezone' requires "
                                  "'as variable' (got %r)" % args)
    return GetCurrentTimezoneNode(args[2])
项目: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
项目:postix    作者:c3cashdesk    | 项目源码 | 文件源码
def get_qr_image(session: CashdeskSession) -> TemporaryFile:
    # TODO: check qr code
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_H,
        box_size=10,
        border=4,
    )
    tz = timezone.get_current_timezone()
    data = '{end}\tEinnahme\t{total}\tKassensession\t#{pk}\t{supervisor}\t{user}'.format(
        end=session.end.astimezone(tz).strftime('%d.%m.%Y\t%H:%M:%S'),
        total='{0:,.2f}'.format(session.get_cash_transaction_total()).translate(str.maketrans(',.', '.,')),
        pk=session.pk,
        supervisor=session.backoffice_user_after.get_full_name(),
        user=session.user.get_full_name(),
    )
    qr.add_data(data)
    qr.make()

    f = TemporaryFile()
    img = qr.make_image()
    img.save(f)
    return f
项目: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
项目: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
项目: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
项目: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
项目: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    作者: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
项目:YouPBX    作者:JoneXiong    | 项目源码 | 文件源码
def lookups(self, request, admin_view):
        now = timezone.now()
        if now.tzinfo is not None:
            current_tz = timezone.get_current_timezone()
            now = now.astimezone(current_tz)
            if hasattr(current_tz, 'normalize'):
                now = current_tz.normalize(now)

        today = now.date()  #now.replace(hour=0, minute=0, second=0, microsecond=0)
        tomorrow = today + datetime.timedelta(days=1)
        return (
            (_('??'), {}),
            (_('Today'), {
                self.lookup_since_name: str(today),
                self.lookup_until_name: str(tomorrow),
            }),
        )
项目:hawkpost    作者:whitesmith    | 项目源码 | 文件源码
def clean_expires_at(self):
        # Validate the expiration date
        expires_at = self.cleaned_data.get("expires_at", "")
        never_expires = self.cleaned_data.get("never_expires", "")
        current_tz = timezone.get_current_timezone()
        if never_expires:
            expires_at = None
            self.cleaned_data["expires_at"] = expires_at
        if expires_at:
            # Check if the expiration date is a past date
            if timezone.localtime(timezone.now(), current_tz) > expires_at:
                self.add_error('expires_at', _('The date must be on the future.'))
        if not expires_at and not never_expires:
            self.add_error('expires_at',
                           _('This field is required, unless box is set to '
                             'never expire.'))
        return expires_at
项目: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 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]
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def datetimes(self, field_name, kind, order='ASC', tzinfo=None):
        """
        Returns a list of datetime objects representing all available
        datetimes for the given field_name, scoped to 'kind'.
        """
        assert kind in ("year", "month", "day", "hour", "minute", "second"), \
            "'kind' must be one of 'year', 'month', 'day', 'hour', 'minute' or 'second'."
        assert order in ('ASC', 'DESC'), \
            "'order' must be either 'ASC' or 'DESC'."
        if settings.USE_TZ:
            if tzinfo is None:
                tzinfo = timezone.get_current_timezone()
        else:
            tzinfo = None
        return self.annotate(
            datetimefield=Trunc(field_name, kind, output_field=DateTimeField(), tzinfo=tzinfo),
            plain_field=F(field_name)
        ).values_list(
            'datetimefield', flat=True
        ).distinct().filter(plain_field__isnull=False).order_by(('-' if order == 'DESC' else '') + 'datetimefield')
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def get_current_timezone_tag(parser, token):
    """
    Stores the name of the current time zone in the context.

    Usage::

        {% get_current_timezone as TIME_ZONE %}

    This will fetch the currently active time zone and put its name
    into the ``TIME_ZONE`` context variable.
    """
    # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
    args = token.contents.split()
    if len(args) != 3 or args[1] != 'as':
        raise TemplateSyntaxError("'get_current_timezone' requires "
                                  "'as variable' (got %r)" % args)
    return GetCurrentTimezoneNode(args[2])
项目: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
项目: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
项目:mobetta    作者:maykinmedia    | 项目源码 | 文件源码
def timestamp_for_metadata(dt=None):
    """
    Return a timestamp with a timezone for the configured locale.  If all else
    fails, consider localtime to be UTC.

    Originally written by Marco Bonetti.
    """
    dt = dt or datetime.datetime.now()
    if timezone is None:
        return dt.strftime('%Y-%m-%d %H:%M%z')
    if not dt.tzinfo:
        tz = timezone.get_current_timezone()
        if not tz:
            tz = timezone.utc
        dt = dt.replace(tzinfo=timezone.get_current_timezone())
    return dt.strftime("%Y-%m-%d %H:%M%z")
项目: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
项目:liberator    作者:libscie    | 项目源码 | 文件源码
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]
项目:liberator    作者:libscie    | 项目源码 | 文件源码
def datetimes(self, field_name, kind, order='ASC', tzinfo=None):
        """
        Returns a list of datetime objects representing all available
        datetimes for the given field_name, scoped to 'kind'.
        """
        assert kind in ("year", "month", "day", "hour", "minute", "second"), \
            "'kind' must be one of 'year', 'month', 'day', 'hour', 'minute' or 'second'."
        assert order in ('ASC', 'DESC'), \
            "'order' must be either 'ASC' or 'DESC'."
        if settings.USE_TZ:
            if tzinfo is None:
                tzinfo = timezone.get_current_timezone()
        else:
            tzinfo = None
        return self.annotate(
            datetimefield=Trunc(field_name, kind, output_field=DateTimeField(), tzinfo=tzinfo),
            plain_field=F(field_name)
        ).values_list(
            'datetimefield', flat=True
        ).distinct().filter(plain_field__isnull=False).order_by(('-' if order == 'DESC' else '') + 'datetimefield')
项目:gmail_scanner    作者:brandonhub    | 项目源码 | 文件源码
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
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
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
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
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]
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
def datetimes(self, field_name, kind, order='ASC', tzinfo=None):
        """
        Returns a list of datetime objects representing all available
        datetimes for the given field_name, scoped to 'kind'.
        """
        assert kind in ("year", "month", "day", "hour", "minute", "second"), \
            "'kind' must be one of 'year', 'month', 'day', 'hour', 'minute' or 'second'."
        assert order in ('ASC', 'DESC'), \
            "'order' must be either 'ASC' or 'DESC'."
        if settings.USE_TZ:
            if tzinfo is None:
                tzinfo = timezone.get_current_timezone()
        else:
            tzinfo = None
        return self.annotate(
            datetimefield=DateTime(field_name, kind, tzinfo),
            plain_field=F(field_name)
        ).values_list(
            'datetimefield', flat=True
        ).distinct().filter(plain_field__isnull=False).order_by(('-' if order == 'DESC' else '') + 'datetimefield')
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
def get_current_timezone_tag(parser, token):
    """
    Stores the name of the current time zone in the context.

    Usage::

        {% get_current_timezone as TIME_ZONE %}

    This will fetch the currently active time zone and put its name
    into the ``TIME_ZONE`` context variable.
    """
    # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
    args = token.contents.split()
    if len(args) != 3 or args[1] != 'as':
        raise TemplateSyntaxError("'get_current_timezone' requires "
                                  "'as variable' (got %r)" % args)
    return GetCurrentTimezoneNode(args[2])
项目:CSCE482-WordcloudPlus    作者:ggaytan00    | 项目源码 | 文件源码
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
项目:tissuelab    作者:VirtualPlants    | 项目源码 | 文件源码
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
项目:api-django    作者:lafranceinsoumise    | 项目源码 | 文件源码
def get_display_date(self):
        tz = timezone.get_current_timezone()
        start_time = self.start_time.astimezone(tz)
        end_time = self.end_time.astimezone(tz)

        if start_time.date() == end_time.date():
            date = formats.date_format(start_time, 'DATE_FORMAT')
            return _("le {date}, de {start_hour} à {end_hour}").format(
                date=date,
                start_hour=formats.time_format(start_time, 'TIME_FORMAT'),
                end_hour=formats.time_format(end_time, 'TIME_FORMAT')
            )

        return _("du {start_date}, {start_time} au {end_date}, {end_time}").format(
            start_date=formats.date_format(start_time, 'DATE_FORMAT'),
            start_time=formats.date_format(start_time, 'TIME_FORMAT'),
            end_date=formats.date_format(end_time, 'DATE_FORMAT'),
            end_time=formats.date_format(end_time, 'TIME_FORMAT'),
        )
项目:producthunt    作者:davidgengler    | 项目源码 | 文件源码
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
项目:django-rtc    作者:scifiswapnil    | 项目源码 | 文件源码
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
项目:geekpoint    作者:Lujinghu    | 项目源码 | 文件源码
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
项目:django-next-train    作者:bitpixdigital    | 项目源码 | 文件源码
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
项目:django-next-train    作者:bitpixdigital    | 项目源码 | 文件源码
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]
项目:django-next-train    作者:bitpixdigital    | 项目源码 | 文件源码
def datetimes(self, field_name, kind, order='ASC', tzinfo=None):
        """
        Returns a list of datetime objects representing all available
        datetimes for the given field_name, scoped to 'kind'.
        """
        assert kind in ("year", "month", "day", "hour", "minute", "second"), \
            "'kind' must be one of 'year', 'month', 'day', 'hour', 'minute' or 'second'."
        assert order in ('ASC', 'DESC'), \
            "'order' must be either 'ASC' or 'DESC'."
        if settings.USE_TZ:
            if tzinfo is None:
                tzinfo = timezone.get_current_timezone()
        else:
            tzinfo = None
        return self.annotate(
            datetimefield=DateTime(field_name, kind, tzinfo),
            plain_field=F(field_name)
        ).values_list(
            'datetimefield', flat=True
        ).distinct().filter(plain_field__isnull=False).order_by(('-' if order == 'DESC' else '') + 'datetimefield')
项目:django-next-train    作者:bitpixdigital    | 项目源码 | 文件源码
def get_current_timezone_tag(parser, token):
    """
    Stores the name of the current time zone in the context.

    Usage::

        {% get_current_timezone as TIME_ZONE %}

    This will fetch the currently active time zone and put its name
    into the ``TIME_ZONE`` context variable.
    """
    # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments
    args = token.contents.split()
    if len(args) != 3 or args[1] != 'as':
        raise TemplateSyntaxError("'get_current_timezone' requires "
                                  "'as variable' (got %r)" % args)
    return GetCurrentTimezoneNode(args[2])