Python django.conf.settings.TIME_ZONE Examples

The following are 30 code examples for showing how to use django.conf.settings.TIME_ZONE(). 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.conf.settings , or try the search function .

Example 1
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def calendar_data(request):
    """
    AJAX JSON results for the calendar (rendered by dashboard.views.calendar)
    """
    try:
        st = iso8601.parse_date(request.GET['start'])
        en = iso8601.parse_date(request.GET['end'])
    except (KeyError, ValueError, iso8601.ParseError):
        return NotFoundResponse(request, errormsg="Bad request")

    user = get_object_or_404(Person, userid=request.user.username)
    local_tz = pytz.timezone(settings.TIME_ZONE)
    start = st - datetime.timedelta(days=1)
    end = en + datetime.timedelta(days=1)

    resp = HttpResponse(content_type="application/json")
    events = _calendar_event_data(user, start, end, local_tz, dt_string=True, colour=True,
            due_before=datetime.timedelta(minutes=1), due_after=datetime.timedelta(minutes=30))
    json.dump(list(events), resp, indent=1)
    return resp 
Example 2
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _offering_meeting_time_data(request, offering):
    """
    fullcalendar.js data for this offering's events
    """
    try:
        st = iso8601.parse_date(request.GET['start'])
        en = iso8601.parse_date(request.GET['end'])
    except (KeyError, ValueError, iso8601.ParseError):
        return NotFoundResponse(request, errormsg="Bad request")

    local_tz = pytz.timezone(settings.TIME_ZONE)
    start = st - datetime.timedelta(days=1)
    end = en + datetime.timedelta(days=1)

    response = HttpResponse(content_type='application/json')
    data = list(_offerings_calendar_data([offering], None, start, end, local_tz,
                                         dt_string=True, colour=True, browse_titles=True))
    json.dump(data, response, indent=1)
    return response 
Example 3
Project: GTDWeb   Author: lanbing510   File: utils.py    License: GNU General Public License v2.0 6 votes vote down vote up
def ensure_defaults(self, alias):
        """
        Puts the defaults into the settings dictionary for a given connection
        where no settings is provided.
        """
        try:
            conn = self.databases[alias]
        except KeyError:
            raise ConnectionDoesNotExist("The connection %s doesn't exist" % alias)

        conn.setdefault('ATOMIC_REQUESTS', False)
        conn.setdefault('AUTOCOMMIT', True)
        conn.setdefault('ENGINE', 'django.db.backends.dummy')
        if conn['ENGINE'] == 'django.db.backends.' or not conn['ENGINE']:
            conn['ENGINE'] = 'django.db.backends.dummy'
        conn.setdefault('CONN_MAX_AGE', 0)
        conn.setdefault('OPTIONS', {})
        conn.setdefault('TIME_ZONE', 'UTC' if settings.USE_TZ else settings.TIME_ZONE)
        for setting in ['NAME', 'USER', 'PASSWORD', 'HOST', 'PORT']:
            conn.setdefault(setting, '') 
Example 4
Project: timed-backend   Author: adfinis-sygroup   File: 0002_auto_20170912_1346.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def migrate_activity_block_time(apps, schema_editor):
    """
    Convert hours to Django time zone.

    Activity block time is in UTC but once it is converted
    to time we actually want time as it would be represented
    in settings.TIME_ZONE
    """
    current_tz = timezone(settings.TIME_ZONE)
    ActivityBlock = apps.get_model("tracking", "ActivityBlock")
    for block in ActivityBlock.objects.all():
        if block.to_datetime is not None:
            block.to_datetime = block.to_datetime.astimezone(current_tz).replace(
                tzinfo=utc
            )
        block.from_datetime = block.from_datetime.astimezone(current_tz).replace(
            tzinfo=utc
        )
        block.save() 
Example 5
Project: bioforum   Author: reBiocoder   File: base.py    License: MIT License 6 votes vote down vote up
def timezone(self):
        """
        Time zone for datetimes stored as naive values in the database.

        Return a tzinfo object or None.

        This is only needed when time zone support is enabled and the database
        doesn't support time zones. (When the database supports time zones,
        the adapter handles aware datetimes so Django doesn't need to.)
        """
        if not settings.USE_TZ:
            return None
        elif self.features.supports_timezones:
            return None
        elif self.settings_dict['TIME_ZONE'] is None:
            return timezone.utc
        else:
            return pytz.timezone(self.settings_dict['TIME_ZONE']) 
Example 6
Project: heartbeats   Author: 510908220   File: check.py    License: MIT License 6 votes vote down vote up
def notify(self, service, now):
        msg = '{service.name}({service.value},{service.grace}) not send heartbeat at {now}'.format(
            service=service,
            now=now.in_timezone(settings.TIME_ZONE).to_datetime_string()
        )
        logger.warning(msg)

        if not service.notify_to.strip():
            logger.warning('service %s notify_to is empty', service.name)
            return

        notify_async(service.notify_to.strip().split(";"),
                     service.name,
                     service.tp,
                     service.value,
                     service.grace,
                     msg
                     ) 
Example 7
Project: heartbeats   Author: 510908220   File: check.py    License: MIT License 6 votes vote down vote up
def process_at_service(self, service):
        """
        当 当前时间 > at时,看[at, at + grace]之间是否有上报的数据
        """
        latest_ping = self.get_last_ping(service)
        if not latest_ping:
            return

        at = pendulum.parse(service.value, tz=settings.TIME_ZONE).in_timezone('UTC')
        last_created = pendulum.instance(latest_ping.created)
        now = pendulum.now(tz='UTC')

        if now < at.add(minutes=int(service.grace)):
            return
        if last_created < at:
            self.notify(service, now) 
Example 8
def get_openrosa_headers(
            self, request, location=True, content_length=True):

        tz = pytz.timezone(settings.TIME_ZONE)
        dt = datetime.now(tz).strftime('%a, %d %b %Y %H:%M:%S %Z')

        data = {
            'Date': dt,
            'X-OpenRosa-Version': '1.0'
        }

        if content_length:
            data['X-OpenRosa-Accept-Content-Length'] = DEFAULT_CONTENT_LENGTH

        if location:
            data['Location'] = request.build_absolute_uri(request.path)

        return data 
Example 9
Project: zing   Author: evernote   File: context_processors.py    License: GNU General Public License v3.0 6 votes vote down vote up
def pootle_context(request):
    """Exposes settings to templates."""
    # FIXME: maybe we should expose relevant settings only?
    return {
        "settings": {
            "ZING_TITLE": settings.ZING_TITLE,
            "ZING_SIGNUP_ENABLED": settings.ZING_SIGNUP_ENABLED,
            "CACHE_TIMEOUT": CACHE_TIMEOUT,
            "CAN_CONTACT": bool(settings.ZING_CONTACT_EMAIL.strip()),
            "TZ": settings.TIME_ZONE,
            "TZ_OFFSET": TZ_OFFSET,
            "DEBUG": settings.DEBUG,
        },
        "ALL_LANGUAGES": Language.live.cached_dict(
            translation.get_language(), request.user.is_superuser
        ),
        "ALL_PROJECTS": Project.objects.cached_dict(request.user),
        "SOCIAL_AUTH_PROVIDERS": _get_social_auth_providers(request),
    } 
Example 10
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: base.py    License: MIT License 6 votes vote down vote up
def timezone(self):
        """
        Time zone for datetimes stored as naive values in the database.

        Return a tzinfo object or None.

        This is only needed when time zone support is enabled and the database
        doesn't support time zones. (When the database supports time zones,
        the adapter handles aware datetimes so Django doesn't need to.)
        """
        if not settings.USE_TZ:
            return None
        elif self.features.supports_timezones:
            return None
        elif self.settings_dict['TIME_ZONE'] is None:
            return timezone.utc
        else:
            return pytz.timezone(self.settings_dict['TIME_ZONE']) 
Example 11
Project: mrs   Author: betagouv   File: models.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def to_date_datetime(date_or_datetime, hour, minute, second, microsecond):
    mytz = pytz.timezone(settings.TIME_ZONE)
    if isinstance(date_or_datetime, datetime.datetime):
        if timezone.is_aware(date_or_datetime):
            date = date_or_datetime.astimezone(mytz)
        else:
            date = mytz.localize(date_or_datetime)
    elif isinstance(date_or_datetime, datetime.date):
        date = date_or_datetime

    return mytz.localize(
        datetime.datetime(
            date.year,
            date.month,
            date.day,
            hour,
            minute,
            second,
            microsecond,
        )
    ) 
Example 12
Project: python   Author: Yeah-Kun   File: base.py    License: Apache License 2.0 6 votes vote down vote up
def timezone(self):
        """
        Time zone for datetimes stored as naive values in the database.

        Returns a tzinfo object or None.

        This is only needed when time zone support is enabled and the database
        doesn't support time zones. (When the database supports time zones,
        the adapter handles aware datetimes so Django doesn't need to.)
        """
        if not settings.USE_TZ:
            return None
        elif self.features.supports_timezones:
            return None
        elif self.settings_dict['TIME_ZONE'] is None:
            return timezone.utc
        else:
            return pytz.timezone(self.settings_dict['TIME_ZONE']) 
Example 13
Project: ontask_b   Author: abelardopardo   File: scheduled_ops.py    License: MIT License 6 votes vote down vote up
def _update_item_status(s_item: models.ScheduledOperation):
    """Update the status of the scheduled item.

    :param s_item: Scheduled item
    :return: Nothing
    """
    now = datetime.now(pytz.timezone(settings.TIME_ZONE))
    if s_item.frequency and (
        not s_item.execute_until or now < s_item.execute_until
    ):
        new_status = models.scheduler.STATUS_PENDING
    else:
        new_status = models.scheduler.STATUS_DONE

    # Save the new status in the DB
    models.ScheduledOperation.objects.filter(pk=s_item.id).update(
        status=new_status)
    s_item.refresh_from_db(fields=['status'])

    if settings.DEBUG:
        CELERY_LOGGER.info('Status set to %s', s_item.status) 
Example 14
Project: luscan-devel   Author: blackye   File: timezone.py    License: GNU General Public License v2.0 6 votes vote down vote up
def get_default_timezone():
    """
    Returns the default time zone as a tzinfo instance.

    This is the time zone defined by settings.TIME_ZONE.

    See also :func:`get_current_timezone`.
    """
    global _localtime
    if _localtime is None:
        if isinstance(settings.TIME_ZONE, six.string_types) and pytz is not None:
            _localtime = pytz.timezone(settings.TIME_ZONE)
        else:
            # This relies on os.environ['TZ'] being set to settings.TIME_ZONE.
            _localtime = LocalTimezone()
    return _localtime

# This function exists for consistency with get_current_timezone_name 
Example 15
Project: luscan-devel   Author: blackye   File: utils.py    License: GNU General Public License v2.0 6 votes vote down vote up
def ensure_defaults(self, alias):
        """
        Puts the defaults into the settings dictionary for a given connection
        where no settings is provided.
        """
        try:
            conn = self.databases[alias]
        except KeyError:
            raise ConnectionDoesNotExist("The connection %s doesn't exist" % alias)

        conn.setdefault('ENGINE', 'django.db.backends.dummy')
        if conn['ENGINE'] == 'django.db.backends.' or not conn['ENGINE']:
            conn['ENGINE'] = 'django.db.backends.dummy'
        conn.setdefault('OPTIONS', {})
        conn.setdefault('TIME_ZONE', 'UTC' if settings.USE_TZ else settings.TIME_ZONE)
        for setting in ['NAME', 'USER', 'PASSWORD', 'HOST', 'PORT']:
            conn.setdefault(setting, '')
        for setting in ['TEST_CHARSET', 'TEST_COLLATION', 'TEST_NAME', 'TEST_MIRROR']:
            conn.setdefault(setting, None) 
Example 16
Project: donation-tracker   Author: GamesDoneQuick   File: test_event.py    License: Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.super_user = User.objects.create_superuser(
            'admin', 'admin@example.com', 'password'
        )
        timezone = pytz.timezone(settings.TIME_ZONE)
        self.event = models.Event.objects.create(
            targetamount=5,
            datetime=today_noon,
            timezone=timezone,
            name='test event',
            short='test',
        )
        self.rand = random.Random(None)
        self.client.force_login(self.super_user) 
Example 17
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def rfc_updated(self):
        """
        Format the updated time in RFC3339 format
        """
        tz = timezone(settings.TIME_ZONE)
        dt = self.updated
        offset = tz.utcoffset(dt)
        return _rfc_format(dt-offset) 
Example 18
Project: GTDWeb   Author: lanbing510   File: timezone.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get_default_timezone():
    """
    Returns the default time zone as a tzinfo instance.

    This is the time zone defined by settings.TIME_ZONE.
    """
    if isinstance(settings.TIME_ZONE, six.string_types) and pytz is not None:
        return pytz.timezone(settings.TIME_ZONE)
    else:
        # This relies on os.environ['TZ'] being set to settings.TIME_ZONE.
        return LocalTimezone()


# This function exists for consistency with get_current_timezone_name 
Example 19
Project: GTDWeb   Author: lanbing510   File: timezone.py    License: GNU General Public License v2.0 5 votes vote down vote up
def deactivate():
    """
    Unsets the time zone for the current thread.

    Django will then use the time zone defined by settings.TIME_ZONE.
    """
    if hasattr(_active, "value"):
        del _active.value 
Example 20
Project: GTDWeb   Author: lanbing510   File: signals.py    License: GNU General Public License v2.0 5 votes vote down vote up
def update_connections_time_zone(**kwargs):
    if kwargs['setting'] == 'TIME_ZONE':
        # Reset process time zone
        if hasattr(time, 'tzset'):
            if kwargs['value']:
                os.environ['TZ'] = kwargs['value']
            else:
                os.environ.pop('TZ', None)
            time.tzset()

        # Reset local time zone cache
        timezone.get_default_timezone.cache_clear()

    # Reset the database connections' time zone
    if kwargs['setting'] == 'USE_TZ' and settings.TIME_ZONE != 'UTC':
        USE_TZ, TIME_ZONE = kwargs['value'], settings.TIME_ZONE
    elif kwargs['setting'] == 'TIME_ZONE' and not settings.USE_TZ:
        USE_TZ, TIME_ZONE = settings.USE_TZ, kwargs['value']
    else:
        # no need to change the database connnections' time zones
        return
    tz = 'UTC' if USE_TZ else TIME_ZONE
    for conn in connections.all():
        conn.settings_dict['TIME_ZONE'] = tz
        tz_sql = conn.ops.set_time_zone_sql()
        if tz_sql:
            conn.cursor().execute(tz_sql, [tz]) 
Example 21
Project: scantron   Author: rackerlabs   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def get_current_time():
    """Retrieve a Django compliant pre-formated datetimestamp."""

    datetime_tz_naive = datetime.datetime.now()
    django_timezone = settings.TIME_ZONE
    datetime_tz = pytz.timezone(django_timezone).localize(datetime_tz_naive)

    return datetime_tz 
Example 22
Project: kobo-predict   Author: awemulya   File: logger_tools.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(BaseOpenRosaResponse, self).__init__(*args, **kwargs)

        self[OPEN_ROSA_VERSION_HEADER] = OPEN_ROSA_VERSION
        tz = pytz.timezone(settings.TIME_ZONE)
        dt = datetime.now(tz).strftime('%a, %d %b %Y %H:%M:%S %Z')
        self['Date'] = dt
        self['X-OpenRosa-Accept-Content-Length'] = DEFAULT_CONTENT_LENGTH
        self['Content-Type'] = DEFAULT_CONTENT_TYPE 
Example 23
Project: kobo-predict   Author: awemulya   File: openrosa_headers_mixin.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_openrosa_headers(self, request, location=True):
        tz = pytz.timezone(settings.TIME_ZONE)
        dt = datetime.now(tz).strftime('%a, %d %b %Y %H:%M:%S %Z')

        data = {
            'Date': dt,
            'X-OpenRosa-Version': '1.0',
            'X-OpenRosa-Accept-Content-Length': DEFAULT_CONTENT_LENGTH
        }

        if location:
            data['Location'] = request.build_absolute_uri(request.path)

        return data 
Example 24
Project: kobo-predict   Author: awemulya   File: fieldsight_logger_tools.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(BaseOpenRosaResponse, self).__init__(*args, **kwargs)

        self[OPEN_ROSA_VERSION_HEADER] = OPEN_ROSA_VERSION
        tz = pytz.timezone(settings.TIME_ZONE)
        dt = datetime.now(tz).strftime('%a, %d %b %Y %H:%M:%S %Z')
        self['Date'] = dt
        self['X-OpenRosa-Accept-Content-Length'] = DEFAULT_CONTENT_LENGTH
        self['Content-Type'] = DEFAULT_CONTENT_TYPE 
Example 25
Project: kobo-predict   Author: awemulya   File: xform_list_api.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_openrosa_headers(self):
        tz = pytz.timezone(settings.TIME_ZONE)
        dt = datetime.now(tz).strftime('%a, %d %b %Y %H:%M:%S %Z')

        return {
            'Date': dt,
            'X-OpenRosa-Version': '1.0',
            'X-OpenRosa-Accept-Content-Length': DEFAULT_CONTENT_LENGTH
        } 
Example 26
Project: django-sundial   Author: charettes   File: tests.py    License: MIT License 5 votes vote down vote up
def test_coercing(self):
        field = TimezoneField()
        self.assertEqual(
            field.clean(settings.TIME_ZONE),
            pytz.timezone(settings.TIME_ZONE)
        ) 
Example 27
Project: django-sundial   Author: charettes   File: tests.py    License: MIT License 5 votes vote down vote up
def test_modelform(self):
        form = TimezoneFieldModelForm({'timezone': settings.TIME_ZONE})
        self.assertTrue(form.is_valid()) 
Example 28
Project: django-sundial   Author: charettes   File: tests.py    License: MIT License 5 votes vote down vote up
def test_coercing(self):
        field = TimezoneChoiceField(choices=ALL_CHOICES)
        self.assertEqual(
            field.clean(settings.TIME_ZONE),
            pytz.timezone(settings.TIME_ZONE)
        ) 
Example 29
Project: django-sundial   Author: charettes   File: tests.py    License: MIT License 5 votes vote down vote up
def test_modelform(self):
        form = TimezoneChoiceFieldModelForm({'choices_timezone': settings.TIME_ZONE})
        self.assertTrue(form.is_valid()) 
Example 30
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)