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

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

项目: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
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def T(self):
        """
        Time zone of this machine; e.g. 'EST' or 'MDT'.

        If timezone information is not available, this method returns
        an empty string.
        """
        if not self.timezone:
            return ""

        name = None
        try:
            name = self.timezone.tzname(self.data)
        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().
            pass
        if name is None:
            name = self.format('O')
        return six.text_type(name)
项目:project-status-dashboard    作者:cmheisel    | 项目源码 | 文件源码
def generate_dashboard():
    logger = logging.getLogger("dashboard.jobs.generate_dashboard")
    logger.info("Start")
    sheet_id = settings.GOOGLE_SPREADSHEET_ID
    data = sheets.load_sheet(sheet_id, settings.GOOGLE_SPREADSHEET_AUTH_FILE)
    for row in data:
        row.xtras = _add_target_date(row.xtras, row.xtras.get('_target_date'))
        if row.xtras.get('_jira_filter'):
            row.xtras = _add_current_jira_summary(row.xtras, row.xtras['_jira_filter'], logger)
        if row.xtras.get('jira_summary'):
            row.xtras = _add_week_ago_summary(row.xtras, row.xtras['jira_summary'], logger)
            row.xtras = _add_forecasts(row.xtras, row.xtras['jira_summary'], logger)
    cache.set('dashboard_data', data, None)
    cache.set('dashboard_data_updated', datetime.datetime.now(get_default_timezone()), None)
    logger.info("End")
    return True
项目:zing    作者:evernote    | 项目源码 | 文件源码
def _add_correction(self, total_amount):
        """Adds a correction for the value of `total_amount` in the month being
        processed.
        """
        server_tz = timezone.get_default_timezone()
        local_now = timezone.localtime(self.now, server_tz)
        initial_moment = local_now.replace(day=1, hour=0, minute=0, second=0)

        PaidTask.objects.get_or_create(
            task_type=PaidTaskTypes.CORRECTION,
            amount=(-1) * total_amount,
            rate=1,
            datetime=self.month_end,
            description='Carryover to the next month',
            user=self.user,
        )
        PaidTask.objects.get_or_create(
            task_type=PaidTaskTypes.CORRECTION,
            amount=total_amount,
            rate=1,
            datetime=initial_moment,
            description='Carryover from the previous month',
            user=self.user,
        )
项目:zing    作者:evernote    | 项目源码 | 文件源码
def get_max_month_datetime(dt):
    """Returns the datetime representing the last microsecond of the month with
    respect to the `dt` aware datetime.
    """
    days_in_month = calendar.monthrange(dt.year, dt.month)[1]

    tz = timezone.get_default_timezone()
    new_dt = tz.normalize(
        dt.replace(day=days_in_month),
    )

    # DST adjustments could have shifted the month or day
    if new_dt.month != dt.month:
        new_dt = new_dt.replace(month=dt.month)
    if new_dt.day != days_in_month:
        new_dt = new_dt.replace(day=days_in_month)

    return new_dt.replace(hour=23, minute=59, second=59, microsecond=999999)
项目: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.
项目: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.
项目: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 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.
项目: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
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def Z(self):
        """
        Time zone offset in seconds (i.e. '-43200' to '43200'). The offset for
        timezones west of UTC is always negative, and for those east of UTC is
        always positive.

        If timezone information is not available, this method returns
        an empty string.
        """
        if not self.timezone:
            return ""

        try:
            offset = self.timezone.utcoffset(self.data)
        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 ""

        # `offset` is a datetime.timedelta. For negative values (to the west of
        # UTC) only days can be negative (days=-1) and seconds are always
        # positive. e.g. UTC-1 -> timedelta(days=-1, seconds=82800, microseconds=0)
        # Positive offsets have days=0
        return offset.days * 86400 + offset.seconds
项目: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
项目:liberator    作者:libscie    | 项目源码 | 文件源码
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
项目:liberator    作者:libscie    | 项目源码 | 文件源码
def Z(self):
        """
        Time zone offset in seconds (i.e. '-43200' to '43200'). The offset for
        timezones west of UTC is always negative, and for those east of UTC is
        always positive.

        If timezone information is not available, this method returns
        an empty string.
        """
        if not self.timezone:
            return ""

        try:
            offset = self.timezone.utcoffset(self.data)
        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 ""

        # `offset` is a datetime.timedelta. For negative values (to the west of
        # UTC) only days can be negative (days=-1) and seconds are always
        # positive. e.g. UTC-1 -> timedelta(days=-1, seconds=82800, microseconds=0)
        # Positive offsets have days=0
        return offset.days * 86400 + offset.seconds
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
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
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
def T(self):
        """
        Time zone of this machine; e.g. 'EST' or 'MDT'.

        If timezone information is not available, this method returns
        an empty string.
        """
        if not self.timezone:
            return ""

        name = None
        try:
            name = self.timezone.tzname(self.data)
        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().
            pass
        if name is None:
            name = self.format('O')
        return six.text_type(name)
项目:django-next-train    作者:bitpixdigital    | 项目源码 | 文件源码
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
项目:django-next-train    作者:bitpixdigital    | 项目源码 | 文件源码
def T(self):
        """
        Time zone of this machine; e.g. 'EST' or 'MDT'.

        If timezone information is not available, this method returns
        an empty string.
        """
        if not self.timezone:
            return ""

        name = None
        try:
            name = self.timezone.tzname(self.data)
        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().
            pass
        if name is None:
            name = self.format('O')
        return six.text_type(name)
项目:LatinSounds_AppEnviaMail    作者:G3ek-aR    | 项目源码 | 文件源码
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
项目:django-wechat-api    作者:crazy-canux    | 项目源码 | 文件源码
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.
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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},
        )
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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 ''
项目:NarshaTech    作者:KimJangHyeon    | 项目源码 | 文件源码
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
项目:zing    作者:evernote    | 项目源码 | 文件源码
def test_make_aware_default_tz(settings):
    """Tests datetimes are made aware of the configured timezone."""
    settings.USE_TZ = True

    datetime_object = datetime(2016, 1, 2, 21, 52, 25)
    assert timezone.is_naive(datetime_object)
    datetime_aware = make_aware(datetime_object)
    assert timezone.is_aware(datetime_aware)

    # Not comparing `tzinfo` directly because that depends on the combination of
    # actual date+times
    assert datetime_aware.tzinfo.zone == timezone.get_default_timezone().zone
项目:zing    作者:evernote    | 项目源码 | 文件源码
def make_aware(value, tz=None):
    """Makes a `datetime` timezone-aware.

    :param value: `datetime` object to make timezone-aware.
    :param tz: `tzinfo` object with the timezone information the given value
        needs to be converted to. By default, site's own default timezone will
        be used.
    """
    if getattr(settings, 'USE_TZ', False) and timezone.is_naive(value):
        use_tz = tz if tz is not None else timezone.get_default_timezone()
        value = timezone.make_aware(value, timezone=use_tz)

    return value
项目:zing    作者:evernote    | 项目源码 | 文件源码
def make_naive(value, tz=None):
    """Makes a `datetime` naive, i.e. not aware of timezones.

    :param value: `datetime` object to make timezone-aware.
    :param tz: `tzinfo` object with the timezone information the given value
        needs to be converted to. By default, site's own default timezone will
        be used.
    """
    if getattr(settings, 'USE_TZ', False) and timezone.is_aware(value):
        use_tz = tz if tz is not None else timezone.get_default_timezone()
        value = timezone.make_naive(value, timezone=use_tz)

    return value
项目:django-admin-rangefilter    作者:silentsokolov    | 项目源码 | 文件源码
def get_timezone(self, request):
        return timezone.get_default_timezone()
项目:Scrum    作者:prakharchoudhary    | 项目源码 | 文件源码
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
项目:django-celery-monitor    作者:jezdez    | 项目源码 | 文件源码
def make_aware(value):
    """Make the given datetime aware of a timezone."""
    if settings.USE_TZ:
        # naive datetimes are assumed to be in UTC.
        if timezone.is_naive(value):
            value = timezone.make_aware(value, timezone.utc)
        # then convert to the Django configured timezone.
        default_tz = timezone.get_default_timezone()
        value = timezone.localtime(value, default_tz)
    return value
项目:django-celery-monitor    作者:jezdez    | 项目源码 | 文件源码
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
项目:DCRM    作者:82Flex    | 项目源码 | 文件源码
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)
项目:django    作者:alexsukhrin    | 项目源码 | 文件源码
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
项目:sdining    作者:Lurance    | 项目源码 | 文件源码
def default_timezone(self):
        return timezone.get_default_timezone() if settings.USE_TZ else None
项目:wagtail_room_booking    作者:Tamriel    | 项目源码 | 文件源码
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
项目:isar    作者:ilbers    | 项目源码 | 文件源码
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)
项目:Gypsy    作者:benticarlos    | 项目源码 | 文件源码
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
项目:DjangoBlog    作者:0daybug    | 项目源码 | 文件源码
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(" "))
项目:jianshu-api    作者:strugglingyouth    | 项目源码 | 文件源码
def default_timezone(self):
        return timezone.get_default_timezone() if settings.USE_TZ else None
项目:trydjango18    作者:wei0104    | 项目源码 | 文件源码
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(" "))
项目:esdc-ce    作者:erigones    | 项目源码 | 文件源码
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)
项目:esdc-ce    作者:erigones    | 项目源码 | 文件源码
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)
项目:esdc-ce    作者:erigones    | 项目源码 | 文件源码
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
项目:ims    作者:ims-team    | 项目源码 | 文件源码
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
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
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
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
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},
        )
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
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
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
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 ''
项目:django-open-lecture    作者:DmLitov4    | 项目源码 | 文件源码
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
项目:LIMS-Backend    作者:LeafLIMS    | 项目源码 | 文件源码
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)