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

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

项目:lenuage    作者:laboiteproject    | 项目源码 | 文件源码
def get_stations(cls, query):
        if query.isdigit():
            query = 'name:{query} OR number:{query}'.format(query=query)
        else:
            # Querying number with a string value raises an error, we remove this field
            query = 'name:{}'.format(query)
        req = requests.get(settings.VELIB_API_BASE_URL,
                           params={'apikey': settings.VELIB_API_KEY,
                                   'dataset': 'stations-velib-disponibilites-en-temps-reel',
                                   'fields': 'number,name',
                                   'q': query,
                                   #'sort': 'name',  Seems to create an error 2016-10-21
                                   'timezone': timezone.get_current_timezone_name()})
        if not req.ok:
            return ()
        data = req.json()
        if not data.get('nhits', 0):
            # No matching data found
            return ()

        return [(item['fields']['number'], item['fields']['name']) for item in data.get('records', [])]
项目:lenuage    作者:laboiteproject    | 项目源码 | 文件源码
def get_station_infos(cls, station_id):
        req = requests.get(settings.VELIB_API_BASE_URL,
                           params={'apikey': settings.VELIB_API_KEY,
                                   'dataset': 'stations-velib-disponibilites-en-temps-reel',
                                   'fields': 'name,bike_stands,available_bikes,status',
                                   'q': 'number:"{}"'.format(station_id),
                                   'timezone': timezone.get_current_timezone_name()})
        if not req.ok:
            return None
        data = req.json()
        if not data.get('nhits', 0):
            # No matching data found
            return None
        data = data['records'][0]['fields']
        return {
            'station': data['name'],
            'slots': data['bike_stands'],
            'bikes': data['available_bikes'],
            'status': data['status'] == 'OPEN'
        }
项目:lenuage    作者:laboiteproject    | 项目源码 | 文件源码
def get_stations(cls, query):
        if query.isdigit():
            query = 'nom:{query} OR idstation:{query}'.format(query=query)
        else:
            # Querying idstation with a string value raises an error, we remove this field
            query = 'nom:{}'.format(query)
        req = requests.get(settings.STAR_API_BASE_URL, params={'apikey': settings.STAR_API_KEY,
                                                          'dataset': 'vls-stations-etat-tr',
                                                          'fields': 'idstation,nom',
                                                          'q': query,
                                                          'sort': 'nom',
                                                          'timezone': timezone.get_current_timezone_name()})
        if not req.ok:
            return ()
        data = req.json()
        if not data.get('nhits', 0):
            # No matching data found
            return ()

        return [(item['fields']['idstation'], item['fields']['nom']) for item in data.get('records', [])]
项目:lenuage    作者:laboiteproject    | 项目源码 | 文件源码
def get_station_infos(cls, station_id):
        req = requests.get(settings.STAR_API_BASE_URL,
                           params={'apikey': settings.STAR_API_KEY,
                                   'dataset': 'vls-stations-etat-tr',
                                   'fields': 'nom,nombreemplacementsactuels,nombrevelosdisponibles,etat',
                                   'q': 'idstation:"{}"'.format(station_id),
                                   'timezone': timezone.get_current_timezone_name()})
        if not req.ok:
            return None
        data = req.json()
        if not data.get('nhits', 0):
            # No matching data found
            return None
        data = data['records'][0]['fields']
        return {
            'station': data['nom'],
            'slots': data['nombreemplacementsactuels'],
            'bikes': data['nombrevelosdisponibles'],
            'status': data['etat'] == 'En fonctionnement'
        }
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
def setUp(self):
        self._timezone_backup = timezone.get_current_timezone_name()
        return super(MiddlewareTests, self).setUp()
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
def test_timezone_awareness(self):
        url = settings.LOGIN_REDIRECT_URL
        mw = middleware.HorizonMiddleware()

        request = self.factory.get(url)
        request.session['django_timezone'] = 'America/Chicago'
        mw.process_request(request)
        self.assertEqual(
            timezone.get_current_timezone_name(), 'America/Chicago')
        request.session['django_timezone'] = 'Europe/Paris'
        mw.process_request(request)
        self.assertEqual(timezone.get_current_timezone_name(), 'Europe/Paris')
        request.session['django_timezone'] = 'UTC'
        mw.process_request(request)
        self.assertEqual(timezone.get_current_timezone_name(), 'UTC')
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def as_sql(self, compiler, connection):
        lhs, lhs_params = compiler.compile(self.lhs)
        tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None
        sql, tz_params = connection.ops.datetime_cast_date_sql(lhs, tzname)
        lhs_params.extend(tz_params)
        return sql, lhs_params
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def as_sql(self, compiler, connection):
        sql, params = compiler.compile(self.lhs)
        lhs_output_field = self.lhs.output_field
        if isinstance(lhs_output_field, DateTimeField):
            tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None
            sql, tz_params = connection.ops.datetime_extract_sql(self.lookup_name, sql, tzname)
            params.extend(tz_params)
        elif isinstance(lhs_output_field, DateField):
            sql = connection.ops.date_extract_sql(self.lookup_name, sql)
        elif isinstance(lhs_output_field, TimeField):
            sql = connection.ops.time_extract_sql(self.lookup_name, sql)
        else:
            raise ValueError('DateTransform only valid on Date/Time/DateTimeFields')
        return sql, params
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def tz(request):
    from django.utils import timezone

    return {'TIME_ZONE': timezone.get_current_timezone_name()}
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def _i18n_cache_key_suffix(request, cache_key):
    """If necessary, adds the current locale or time zone to the cache key."""
    if settings.USE_I18N or settings.USE_L10N:
        # first check if LocaleMiddleware or another middleware added
        # LANGUAGE_CODE to request, then fall back to the active language
        # which in turn can also fall back to settings.LANGUAGE_CODE
        cache_key += '.%s' % getattr(request, 'LANGUAGE_CODE', get_language())
    if settings.USE_TZ:
        # The datetime module doesn't restrict the output of tzname().
        # Windows is known to use non-standard, locale-dependent names.
        # User-defined tzinfo classes may return absolutely anything.
        # Hence this paranoid conversion to create a valid cache key.
        tz_name = force_text(get_current_timezone_name(), errors='ignore')
        cache_key += '.%s' % tz_name.encode('ascii', 'ignore').decode('ascii').replace(' ', '_')
    return cache_key
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def render(self, context):
        context[self.variable] = timezone.get_current_timezone_name()
        return ''
项目:pretalx    作者:pretalx    | 项目源码 | 文件源码
def save(self):
        data = self.cleaned_data
        if data.get('register_username') and data.get('register_email') and data.get('register_password'):
            user = User.objects.create_user(nick=data.get('register_username'),
                                            email=data.get('register_email'),
                                            password=data.get('register_password'),
                                            locale=translation.get_language(),
                                            timezone=timezone.get_current_timezone_name())
            data['user_id'] = user.pk

        return data['user_id']
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def test_submission_count_for_today_in_form_list(self):

        self._publish_xls_form_to_project()
        request = self.factory.get('/', **self.extra)
        response = self.view(request)
        self.assertEqual(response.status_code, 200)
        self.assertIn('submission_count_for_today', response.data[0].keys())
        self.assertEqual(response.data[0]['submission_count_for_today'], 0)
        self.assertEqual(response.data[0]['num_of_submissions'], 0)

        paths = [os.path.join(
            self.main_directory, 'fixtures', 'transportation',
            'instances_w_uuid', s, s + '.xml')
            for s in ['transport_2011-07-25_19-05-36']]

        # instantiate date that is NOT naive; timezone is enabled
        current_timzone_name = timezone.get_current_timezone_name()
        current_timezone = pytz.timezone(current_timzone_name)
        today = datetime.today()
        current_date = current_timezone.localize(
            datetime(today.year,
                     today.month,
                     today.day))
        self._make_submission(paths[0], forced_submission_time=current_date)
        self.assertEqual(self.response.status_code, 201)

        request = self.factory.get('/', **self.extra)
        response = self.view(request)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data[0]['submission_count_for_today'], 1)
        self.assertEqual(response.data[0]['num_of_submissions'], 1)
项目:fieldsight-kobocat    作者:awemulya    | 项目源码 | 文件源码
def submission_count_for_today(self):
        current_timzone_name = timezone.get_current_timezone_name()
        current_timezone = pytz.timezone(current_timzone_name)
        today = datetime.today()
        current_date = current_timezone.localize(
            datetime(today.year,
                     today.month,
                     today.day))
        count = self.instances.filter(
            deleted_at__isnull=True,
            date_created=current_date).count()
        return count
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def get_tzname(self):
        # Timezone conversions must happen to the input datetime *before*
        # applying a function. 2015-12-31 23:00:00 -02:00 is stored in the
        # database as 2016-01-01 01:00:00 +00:00. Any results should be
        # based on the input datetime not the stored datetime.
        tzname = None
        if settings.USE_TZ:
            if self.tzinfo is None:
                tzname = timezone.get_current_timezone_name()
            else:
                tzname = timezone._get_timezone_name(self.tzinfo)
        return tzname
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def as_sql(self, compiler, connection):
        # Cast to date rather than truncate to date.
        lhs, lhs_params = compiler.compile(self.lhs)
        tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None
        sql, tz_params = connection.ops.datetime_cast_date_sql(lhs, tzname)
        lhs_params.extend(tz_params)
        return sql, lhs_params
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def as_sql(self, compiler, connection):
        # Cast to date rather than truncate to date.
        lhs, lhs_params = compiler.compile(self.lhs)
        tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None
        sql, tz_params = connection.ops.datetime_cast_time_sql(lhs, tzname)
        lhs_params.extend(tz_params)
        return sql, lhs_params
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def tz(request):
    from django.utils import timezone
    return {'TIME_ZONE': timezone.get_current_timezone_name()}
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def _i18n_cache_key_suffix(request, cache_key):
    """If necessary, adds the current locale or time zone to the cache key."""
    if settings.USE_I18N or settings.USE_L10N:
        # first check if LocaleMiddleware or another middleware added
        # LANGUAGE_CODE to request, then fall back to the active language
        # which in turn can also fall back to settings.LANGUAGE_CODE
        cache_key += '.%s' % getattr(request, 'LANGUAGE_CODE', get_language())
    if settings.USE_TZ:
        # The datetime module doesn't restrict the output of tzname().
        # Windows is known to use non-standard, locale-dependent names.
        # User-defined tzinfo classes may return absolutely anything.
        # Hence this paranoid conversion to create a valid cache key.
        tz_name = force_text(get_current_timezone_name(), errors='ignore')
        cache_key += '.%s' % tz_name.encode('ascii', 'ignore').decode('ascii').replace(' ', '_')
    return cache_key
项目:DjangoCMS    作者:farhan711    | 项目源码 | 文件源码
def _placeholder_cache_key(placeholder, lang):
    cache_key = '%srender_placeholder:%s.%s' % (get_cms_setting("CACHE_PREFIX"), placeholder.pk, str(lang))
    if settings.USE_TZ:
        tz_name = force_text(get_current_timezone_name(), errors='ignore')
        cache_key += '.%s' % tz_name.encode('ascii', 'ignore').decode('ascii').replace(' ', '_')
    return cache_key
项目:DjangoCMS    作者:farhan711    | 项目源码 | 文件源码
def _page_cache_key(request):
    #md5 key of current path
    cache_key = "%s:%d:%s" % (
        get_cms_setting("CACHE_PREFIX"),
        settings.SITE_ID,
        hashlib.md5(iri_to_uri(request.get_full_path()).encode('utf-8')).hexdigest()
    )
    if settings.USE_TZ:
        # The datetime module doesn't restrict the output of tzname().
        # Windows is known to use non-standard, locale-dependant names.
        # User-defined tzinfo classes may return absolutely anything.
        # Hence this paranoid conversion to create a valid cache key.
        tz_name = force_text(get_current_timezone_name(), errors='ignore')
        cache_key += '.%s' % tz_name.encode('ascii', 'ignore').decode('ascii').replace(' ', '_')
    return cache_key
项目:liberator    作者:libscie    | 项目源码 | 文件源码
def get_tzname(self):
        # Timezone conversions must happen to the input datetime *before*
        # applying a function. 2015-12-31 23:00:00 -02:00 is stored in the
        # database as 2016-01-01 01:00:00 +00:00. Any results should be
        # based on the input datetime not the stored datetime.
        tzname = None
        if settings.USE_TZ:
            if self.tzinfo is None:
                tzname = timezone.get_current_timezone_name()
            else:
                tzname = timezone._get_timezone_name(self.tzinfo)
        return tzname
项目:liberator    作者:libscie    | 项目源码 | 文件源码
def as_sql(self, compiler, connection):
        # Cast to date rather than truncate to date.
        lhs, lhs_params = compiler.compile(self.lhs)
        tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None
        sql, tz_params = connection.ops.datetime_cast_date_sql(lhs, tzname)
        lhs_params.extend(tz_params)
        return sql, lhs_params
项目:liberator    作者:libscie    | 项目源码 | 文件源码
def as_sql(self, compiler, connection):
        # Cast to date rather than truncate to date.
        lhs, lhs_params = compiler.compile(self.lhs)
        tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None
        sql, tz_params = connection.ops.datetime_cast_time_sql(lhs, tzname)
        lhs_params.extend(tz_params)
        return sql, lhs_params
项目:liberator    作者:libscie    | 项目源码 | 文件源码
def tz(request):
    from django.utils import timezone
    return {'TIME_ZONE': timezone.get_current_timezone_name()}
项目:liberator    作者:libscie    | 项目源码 | 文件源码
def _i18n_cache_key_suffix(request, cache_key):
    """If necessary, adds the current locale or time zone to the cache key."""
    if settings.USE_I18N or settings.USE_L10N:
        # first check if LocaleMiddleware or another middleware added
        # LANGUAGE_CODE to request, then fall back to the active language
        # which in turn can also fall back to settings.LANGUAGE_CODE
        cache_key += '.%s' % getattr(request, 'LANGUAGE_CODE', get_language())
    if settings.USE_TZ:
        # The datetime module doesn't restrict the output of tzname().
        # Windows is known to use non-standard, locale-dependent names.
        # User-defined tzinfo classes may return absolutely anything.
        # Hence this paranoid conversion to create a valid cache key.
        tz_name = force_text(get_current_timezone_name(), errors='ignore')
        cache_key += '.%s' % tz_name.encode('ascii', 'ignore').decode('ascii').replace(' ', '_')
    return cache_key
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
def as_sql(self, compiler, connection):
        lhs, lhs_params = compiler.compile(self.lhs)
        tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None
        sql, tz_params = connection.ops.datetime_cast_date_sql(lhs, tzname)
        lhs_params.extend(tz_params)
        return sql, lhs_params
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
def as_sql(self, compiler, connection):
        sql, params = compiler.compile(self.lhs)
        lhs_output_field = self.lhs.output_field
        if isinstance(lhs_output_field, DateTimeField):
            tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None
            sql, tz_params = connection.ops.datetime_extract_sql(self.lookup_name, sql, tzname)
            params.extend(tz_params)
        elif isinstance(lhs_output_field, DateField):
            sql = connection.ops.date_extract_sql(self.lookup_name, sql)
        elif isinstance(lhs_output_field, TimeField):
            sql = connection.ops.time_extract_sql(self.lookup_name, sql)
        else:
            raise ValueError('DateTransform only valid on Date/Time/DateTimeFields')
        return sql, params
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
def tz(request):
    from django.utils import timezone

    return {'TIME_ZONE': timezone.get_current_timezone_name()}
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
def _i18n_cache_key_suffix(request, cache_key):
    """If necessary, adds the current locale or time zone to the cache key."""
    if settings.USE_I18N or settings.USE_L10N:
        # first check if LocaleMiddleware or another middleware added
        # LANGUAGE_CODE to request, then fall back to the active language
        # which in turn can also fall back to settings.LANGUAGE_CODE
        cache_key += '.%s' % getattr(request, 'LANGUAGE_CODE', get_language())
    if settings.USE_TZ:
        # The datetime module doesn't restrict the output of tzname().
        # Windows is known to use non-standard, locale-dependent names.
        # User-defined tzinfo classes may return absolutely anything.
        # Hence this paranoid conversion to create a valid cache key.
        tz_name = force_text(get_current_timezone_name(), errors='ignore')
        cache_key += '.%s' % tz_name.encode('ascii', 'ignore').decode('ascii').replace(' ', '_')
    return cache_key
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
def render(self, context):
        context[self.variable] = timezone.get_current_timezone_name()
        return ''
项目:tissuelab    作者:VirtualPlants    | 项目源码 | 文件源码
def tz(request):
    from django.utils import timezone

    return {'TIME_ZONE': timezone.get_current_timezone_name()}
项目:django-next-train    作者:bitpixdigital    | 项目源码 | 文件源码
def as_sql(self, compiler, connection):
        lhs, lhs_params = compiler.compile(self.lhs)
        tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None
        sql, tz_params = connection.ops.datetime_cast_date_sql(lhs, tzname)
        lhs_params.extend(tz_params)
        return sql, lhs_params
项目:django-next-train    作者:bitpixdigital    | 项目源码 | 文件源码
def as_sql(self, compiler, connection):
        sql, params = compiler.compile(self.lhs)
        lhs_output_field = self.lhs.output_field
        if isinstance(lhs_output_field, DateTimeField):
            tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None
            sql, tz_params = connection.ops.datetime_extract_sql(self.lookup_name, sql, tzname)
            params.extend(tz_params)
        elif isinstance(lhs_output_field, DateField):
            sql = connection.ops.date_extract_sql(self.lookup_name, sql)
        elif isinstance(lhs_output_field, TimeField):
            sql = connection.ops.time_extract_sql(self.lookup_name, sql)
        else:
            raise ValueError('DateTransform only valid on Date/Time/DateTimeFields')
        return sql, params
项目:django-next-train    作者:bitpixdigital    | 项目源码 | 文件源码
def tz(request):
    from django.utils import timezone

    return {'TIME_ZONE': timezone.get_current_timezone_name()}
项目:django-next-train    作者:bitpixdigital    | 项目源码 | 文件源码
def _i18n_cache_key_suffix(request, cache_key):
    """If necessary, adds the current locale or time zone to the cache key."""
    if settings.USE_I18N or settings.USE_L10N:
        # first check if LocaleMiddleware or another middleware added
        # LANGUAGE_CODE to request, then fall back to the active language
        # which in turn can also fall back to settings.LANGUAGE_CODE
        cache_key += '.%s' % getattr(request, 'LANGUAGE_CODE', get_language())
    if settings.USE_TZ:
        # The datetime module doesn't restrict the output of tzname().
        # Windows is known to use non-standard, locale-dependent names.
        # User-defined tzinfo classes may return absolutely anything.
        # Hence this paranoid conversion to create a valid cache key.
        tz_name = force_text(get_current_timezone_name(), errors='ignore')
        cache_key += '.%s' % tz_name.encode('ascii', 'ignore').decode('ascii').replace(' ', '_')
    return cache_key
项目:django-next-train    作者:bitpixdigital    | 项目源码 | 文件源码
def render(self, context):
        context[self.variable] = timezone.get_current_timezone_name()
        return ''
项目:FormShare    作者:qlands    | 项目源码 | 文件源码
def test_submission_count_for_today_in_form_list(self):

        self._publish_xls_form_to_project()
        request = self.factory.get('/', **self.extra)
        response = self.view(request)
        self.assertNotEqual(response.get('Last-Modified'), None)
        self.assertEqual(response.status_code, 200)
        self.assertIn('submission_count_for_today', response.data[0].keys())
        self.assertEqual(response.data[0]['submission_count_for_today'], 0)
        self.assertEqual(response.data[0]['num_of_submissions'], 0)

        paths = [os.path.join(
            self.main_directory, 'fixtures', 'transportation',
            'instances_w_uuid', s, s + '.xml')
            for s in ['transport_2011-07-25_19-05-36']]

        # instantiate date that is NOT naive; timezone is enabled
        current_timzone_name = timezone.get_current_timezone_name()
        current_timezone = pytz.timezone(current_timzone_name)
        today = datetime.today()
        current_date = current_timezone.localize(
            datetime(today.year,
                     today.month,
                     today.day))
        self._make_submission(paths[0], forced_submission_time=current_date)
        self.assertEqual(self.response.status_code, 201)

        request = self.factory.get('/', **self.extra)
        response = self.view(request)
        self.assertNotEqual(response.get('Last-Modified'), None)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data[0]['submission_count_for_today'], 1)
        self.assertEqual(response.data[0]['num_of_submissions'], 1)
项目:FormShare    作者:qlands    | 项目源码 | 文件源码
def submission_count_for_today(self):
        current_timzone_name = timezone.get_current_timezone_name()
        current_timezone = pytz.timezone(current_timzone_name)
        today = datetime.today()
        current_date = current_timezone.localize(
            datetime(today.year,
                     today.month,
                     today.day))
        count = self.instances.filter(
            deleted_at__isnull=True,
            date_created=current_date).count()
        return count
项目:LatinSounds_AppEnviaMail    作者:G3ek-aR    | 项目源码 | 文件源码
def get_tzname(self):
        # Timezone conversions must happen to the input datetime *before*
        # applying a function. 2015-12-31 23:00:00 -02:00 is stored in the
        # database as 2016-01-01 01:00:00 +00:00. Any results should be
        # based on the input datetime not the stored datetime.
        tzname = None
        if settings.USE_TZ:
            if self.tzinfo is None:
                tzname = timezone.get_current_timezone_name()
            else:
                tzname = timezone._get_timezone_name(self.tzinfo)
        return tzname
项目:LatinSounds_AppEnviaMail    作者:G3ek-aR    | 项目源码 | 文件源码
def as_sql(self, compiler, connection):
        # Cast to date rather than truncate to date.
        lhs, lhs_params = compiler.compile(self.lhs)
        tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None
        sql, tz_params = connection.ops.datetime_cast_date_sql(lhs, tzname)
        lhs_params.extend(tz_params)
        return sql, lhs_params
项目:LatinSounds_AppEnviaMail    作者:G3ek-aR    | 项目源码 | 文件源码
def as_sql(self, compiler, connection):
        # Cast to date rather than truncate to date.
        lhs, lhs_params = compiler.compile(self.lhs)
        tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None
        sql, tz_params = connection.ops.datetime_cast_time_sql(lhs, tzname)
        lhs_params.extend(tz_params)
        return sql, lhs_params
项目:a4-opin    作者:liqd    | 项目源码 | 文件源码
def test_request_processed_user(rf, user):
    request = rf.get('/')
    request.user = user
    TimezoneMiddleware().process_request(request)
    assert user.timezone == timezone.get_current_timezone_name()
项目:a4-opin    作者:liqd    | 项目源码 | 文件源码
def test_request_processed_default(rf):
    request = rf.get('/')
    user = AnonymousUser()
    request.user = user
    TimezoneMiddleware().process_request(request)
    assert settings.TIME_ZONE == timezone.get_current_timezone_name()
项目:django-wechat-api    作者:crazy-canux    | 项目源码 | 文件源码
def process_lhs(self, compiler, connection, lhs=None):
        from django.db.models import DateTimeField
        lhs, params = super(DateLookup, self).process_lhs(compiler, connection, lhs)
        if isinstance(self.lhs.output_field, DateTimeField):
            tzname = timezone.get_current_timezone_name() if settings.USE_TZ else None
            sql, tz_params = connection.ops.datetime_extract_sql(self.extract_type, lhs, tzname)
            return connection.ops.lookup_cast(self.lookup_name) % sql, tz_params
        else:
            return connection.ops.date_extract_sql(self.lookup_name, lhs), []
项目:django-wechat-api    作者:crazy-canux    | 项目源码 | 文件源码
def tz(request):
    from django.utils import timezone

    return {'TIME_ZONE': timezone.get_current_timezone_name()}
项目:django-wechat-api    作者:crazy-canux    | 项目源码 | 文件源码
def _i18n_cache_key_suffix(request, cache_key):
    """If necessary, adds the current locale or time zone to the cache key."""
    if settings.USE_I18N or settings.USE_L10N:
        # first check if LocaleMiddleware or another middleware added
        # LANGUAGE_CODE to request, then fall back to the active language
        # which in turn can also fall back to settings.LANGUAGE_CODE
        cache_key += '.%s' % getattr(request, 'LANGUAGE_CODE', get_language())
    if settings.USE_TZ:
        # The datetime module doesn't restrict the output of tzname().
        # Windows is known to use non-standard, locale-dependent names.
        # User-defined tzinfo classes may return absolutely anything.
        # Hence this paranoid conversion to create a valid cache key.
        tz_name = force_text(get_current_timezone_name(), errors='ignore')
        cache_key += '.%s' % tz_name.encode('ascii', 'ignore').decode('ascii').replace(' ', '_')
    return cache_key
项目:django-wechat-api    作者:crazy-canux    | 项目源码 | 文件源码
def render(self, context):
        context[self.variable] = timezone.get_current_timezone_name()
        return ''
项目:django-trackstats    作者:pennersr    | 项目源码 | 文件源码
def track(self, qs):
        to_date = date.today()
        start_date = self.get_start_date(qs)
        if not start_date:
            return
        if self.period == Period.LIFETIME:
            # Intentionally recompute last stat, as we may have computed
            # that the last time when the day was not over yet.
            upto_date = start_date
            while upto_date <= to_date:
                self.track_lifetime_upto(qs, upto_date)
                upto_date += timedelta(days=1)
        elif self.period == Period.DAY:
            values_fields = ['ts_date'] + self.get_track_values()
            connection = connections[qs.db]
            tzname = (
                timezone.get_current_timezone_name()
                if settings.USE_TZ else None)

            is_datetime = isinstance(qs.model._meta.get_field(
                self.date_field), models.DateTimeField)
            if is_datetime:
                date_sql, tz_params = connection.ops.datetime_cast_date_sql(
                    self.date_field,
                    tzname)
                vals = qs.extra(
                    select={"ts_date": date_sql},
                    select_params=tz_params)
                start_dt = datetime.combine(
                    start_date, time()) - timedelta(days=1)
                if tzname:
                    start_dt = timezone.make_aware(
                        start_dt,
                        timezone.get_current_timezone())
            else:
                vals = qs.extra(select={"ts_date": self.date_field})
                start_dt = start_date
            vals = vals.filter(
                **{self.date_field + '__gte': start_dt}).values(
                *values_fields).order_by().annotate(ts_n=self.aggr_op)
            # TODO: Bulk create
            for val in vals:
                self.statistic_model.objects.record(
                    metric=self.metric,
                    value=val['ts_n'],
                    date=val['ts_date'],
                    period=self.period,
                    **self.get_record_kwargs(val))
        else:
            raise NotImplementedError