Python django.utils.timezone.get_current_timezone_name() Examples

The following are 30 code examples for showing how to use django.utils.timezone.get_current_timezone_name(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.utils.timezone , or try the search function .

Example 1
Project: ls.joyous   Author: linuxsoftware   File: edit_handlers.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def on_instance_bound(self):
        super().on_instance_bound()
        if not self.form:
            # wait for the form to be set, it will eventually be
            return
        if not self.instance.overrides:
            return
        widget = self.form[self.field_name].field.widget
        widget.overrides_repeat = self.instance.overrides_repeat
        tz = timezone._get_timezone_name(self.instance.tz)
        if tz != timezone.get_current_timezone_name():
            self.exceptionTZ = tz
        else:
            self.exceptionTZ = None

# ------------------------------------------------------------------------------ 
Example 2
Project: GTDWeb   Author: lanbing510   File: tz.py    License: GNU General Public License v2.0 5 votes vote down vote up
def render(self, context):
        context[self.variable] = timezone.get_current_timezone_name()
        return '' 
Example 3
Project: GTDWeb   Author: lanbing510   File: cache.py    License: GNU General Public License v2.0 5 votes vote down vote up
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 
Example 4
Project: GTDWeb   Author: lanbing510   File: lookups.py    License: GNU General Public License v2.0 5 votes vote down vote up
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), [] 
Example 5
Project: GTDWeb   Author: lanbing510   File: context_processors.py    License: GNU General Public License v2.0 5 votes vote down vote up
def tz(request):
    from django.utils import timezone

    return {'TIME_ZONE': timezone.get_current_timezone_name()} 
Example 6
Project: kobo-predict   Author: awemulya   File: test_xform_viewset.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
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) 
Example 7
Project: kobo-predict   Author: awemulya   File: xform.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 
Example 8
Project: django-sundial   Author: charettes   File: test_middleware.py    License: MIT License 5 votes vote down vote up
def test_missing_session(self):
        request = self.request_factory.get('/')
        self.middleware.process_request(request)
        self.assertEqual(timezone.get_current_timezone_name(), settings.TIME_ZONE) 
Example 9
Project: django-sundial   Author: charettes   File: test_middleware.py    License: MIT License 5 votes vote down vote up
def test_missing_session_timezone(self):
        request = self.request_factory.get('/')
        self.session_middleware.process_request(request)
        self.middleware.process_request(request)
        self.assertEqual(timezone.get_current_timezone_name(), settings.TIME_ZONE) 
Example 10
Project: django-sundial   Author: charettes   File: test_middleware.py    License: MIT License 5 votes vote down vote up
def test_timezone_activation(self):
        request = self.request_factory.get('/')
        self.session_middleware.process_request(request)
        zone = 'America/Montreal'
        set_session_timezone(request.session, zone)
        self.middleware.process_request(request)
        self.assertEqual(timezone.get_current_timezone_name(), zone) 
Example 11
Project: bioforum   Author: reBiocoder   File: tz.py    License: MIT License 5 votes vote down vote up
def render(self, context):
        context[self.variable] = timezone.get_current_timezone_name()
        return '' 
Example 12
Project: bioforum   Author: reBiocoder   File: cache.py    License: MIT License 5 votes vote down vote up
def _i18n_cache_key_suffix(request, cache_key):
    """If necessary, add 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 
Example 13
Project: bioforum   Author: reBiocoder   File: datetime.py    License: MIT License 5 votes vote down vote up
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 
Example 14
Project: bioforum   Author: reBiocoder   File: datetime.py    License: MIT License 5 votes vote down vote up
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 = connection.ops.datetime_cast_date_sql(lhs, tzname)
        return sql, lhs_params 
Example 15
Project: bioforum   Author: reBiocoder   File: datetime.py    License: MIT License 5 votes vote down vote up
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 = connection.ops.datetime_cast_time_sql(lhs, tzname)
        return sql, lhs_params 
Example 16
Project: django-aws-template   Author: dkarchmer   File: tests.py    License: MIT License 5 votes vote down vote up
def testTimeZone(self):
        #tzname = request.session.get('django_timezone')
        response = self.client.get('/')
        self.failUnlessEqual(response.status_code, status.HTTP_200_OK)

        # If not loggedin, no timezone in session
        session = self.client.session
        self.assertFalse('django_timezone' in session)

        ok = self.client.login(email='user1@foo.com', password='pass')
        self.assertTrue(ok)
        response = self.client.get('/')
        self.failUnlessEqual(response.status_code, status.HTTP_200_OK)

        # Default Time zone
        session = self.client.session
        self.assertTrue('django_timezone' in session)
        self.assertEqual(session["django_timezone"], timezone.get_default_timezone_name())

        self.client.logout()

        u4 = user_model.objects.create_user(username='user4', email='user4@foo.com', password='pass')
        u4.name = 'New York Dude'
        u4.time_zone = 'America/New_York'
        u4.is_active = True
        u4.save()

        ok = self.client.login(email='user4@foo.com', password='pass')
        self.assertTrue(ok)
        response = self.client.get('/')
        self.failUnlessEqual(response.status_code, status.HTTP_200_OK)

        # Default Time zone
        session = self.client.session
        self.assertTrue('django_timezone' in session)
        self.assertEqual(session["django_timezone"], timezone.get_current_timezone_name())
        self.assertEqual(timezone.get_current_timezone_name(), 'America/New_York')

        self.client.logout() 
Example 17
Project: zulip   Author: zulip   File: signals.py    License: Apache License 2.0 5 votes vote down vote up
def email_on_new_login(sender: Any, user: UserProfile, request: Any, **kwargs: Any) -> None:
    if not user.enable_login_emails:
        return
    # We import here to minimize the dependencies of this module,
    # since it runs as part of `manage.py` initialization
    from zerver.context_processors import common_context

    if not settings.SEND_LOGIN_EMAILS:
        return

    if request:
        # If the user's account was just created, avoid sending an email.
        if (timezone_now() - user.date_joined).total_seconds() <= JUST_CREATED_THRESHOLD:
            return

        user_agent = request.META.get('HTTP_USER_AGENT', "").lower()

        context = common_context(user)
        context['user_email'] = user.delivery_email
        user_tz = user.timezone
        if user_tz == '':
            user_tz = timezone_get_current_timezone_name()
        local_time = timezone_now().astimezone(get_timezone(user_tz))
        if user.twenty_four_hour_time:
            hhmm_string = local_time.strftime('%H:%M')
        else:
            hhmm_string = local_time.strftime('%I:%M%p')
        context['login_time'] = local_time.strftime(f'%A, %B %d, %Y at {hhmm_string} %Z')
        context['device_ip'] = request.META.get('REMOTE_ADDR') or _("Unknown IP address")
        context['device_os'] = get_device_os(user_agent) or _("an unknown operating system")
        context['device_browser'] = get_device_browser(user_agent) or _("An unknown browser")
        context['unsubscribe_link'] = one_click_unsubscribe_link(user, 'login')

        email_dict = {
            'template_prefix': 'zerver/emails/notify_new_login',
            'to_user_ids': [user.id],
            'from_name': FromAddress.security_email_from_name(user_profile=user),
            'from_address': FromAddress.NOREPLY,
            'context': context}
        queue_json_publish("email_senders", email_dict) 
Example 18
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: tz.py    License: MIT License 5 votes vote down vote up
def render(self, context):
        context[self.variable] = timezone.get_current_timezone_name()
        return '' 
Example 19
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: cache.py    License: MIT License 5 votes vote down vote up
def _i18n_cache_key_suffix(request, cache_key):
    """If necessary, add 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:
        cache_key += '.%s' % get_current_timezone_name()
    return cache_key 
Example 20
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: datetime.py    License: MIT License 5 votes vote down vote up
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 
Example 21
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: datetime.py    License: MIT License 5 votes vote down vote up
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 = connection.ops.datetime_cast_date_sql(lhs, tzname)
        return sql, lhs_params 
Example 22
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: datetime.py    License: MIT License 5 votes vote down vote up
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 = connection.ops.datetime_cast_time_sql(lhs, tzname)
        return sql, lhs_params 
Example 23
Project: python   Author: Yeah-Kun   File: tz.py    License: Apache License 2.0 5 votes vote down vote up
def render(self, context):
        context[self.variable] = timezone.get_current_timezone_name()
        return '' 
Example 24
Project: python   Author: Yeah-Kun   File: cache.py    License: Apache License 2.0 5 votes vote down vote up
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 
Example 25
Project: python   Author: Yeah-Kun   File: datetime.py    License: Apache License 2.0 5 votes vote down vote up
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 
Example 26
Project: python   Author: Yeah-Kun   File: datetime.py    License: Apache License 2.0 5 votes vote down vote up
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 
Example 27
Project: python   Author: Yeah-Kun   File: datetime.py    License: Apache License 2.0 5 votes vote down vote up
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 
Example 28
Project: luscan-devel   Author: blackye   File: tz.py    License: GNU General Public License v2.0 5 votes vote down vote up
def render(self, context):
        context[self.variable] = timezone.get_current_timezone_name()
        return '' 
Example 29
Project: luscan-devel   Author: blackye   File: cache.py    License: GNU General Public License v2.0 5 votes vote down vote up
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-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 
Example 30
Project: luscan-devel   Author: blackye   File: context_processors.py    License: GNU General Public License v2.0 5 votes vote down vote up
def tz(request):
    from django.utils import timezone

    return {'TIME_ZONE': timezone.get_current_timezone_name()}