Python django.conf.settings.TIME_ZONE Examples

The following are 30 code examples of django.conf.settings.TIME_ZONE(). 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 also want to check out all available functions/classes of the module django.conf.settings , or try the search function .
Example #1
Source File: openrosa_headers_mixin.py    From cadasta-platform with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #2
Source File: 0002_auto_20170912_1346.py    From timed-backend with 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 #3
Source File: base.py    From python with 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 #4
Source File: models.py    From mrs with 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 #5
Source File: base.py    From bioforum with 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
Source File: base.py    From Hands-On-Application-Development-with-PyCharm with 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 #7
Source File: scheduled_ops.py    From ontask_b with 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 #8
Source File: check.py    From heartbeats with 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 #9
Source File: check.py    From heartbeats with 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 #10
Source File: utils.py    From GTDWeb with 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 #11
Source File: timezone.py    From luscan-devel with 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 #12
Source File: context_processors.py    From zing with 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 #13
Source File: views.py    From coursys with 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 #14
Source File: utils.py    From luscan-devel with 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 #15
Source File: views.py    From coursys with 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 #16
Source File: timezone.py    From luscan-devel with 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 #17
Source File: column.py    From ontask_b with MIT License 5 votes vote down vote up
def is_active(self) -> bool:
        """Check if a column is active.

        The current time is within the
        interval defined by active_from - active_to.

        :return: Boolean encoding the active status
        """
        now = datetime.datetime.now(pytz.timezone(settings.TIME_ZONE))
        return not (
            (self.active_from and now < self.active_from)
            or (self.active_to and self.active_to < now)) 
Example #18
Source File: test_scheduled_actions.py    From ontask_b with MIT License 5 votes vote down vote up
def test_scheduled_json_report_action(self):
        """Create a scheduled send report action and execute it."""

        token = 'false token'
        settings.EXECUTE_ACTION_JSON_TRANSFER = False
        OnTaskSharedState.json_outbox = []

        user = get_user_model().objects.get(email='instructor01@bogus.com')

        # User must exist
        self.assertIsNotNone(user, 'User instructor01@bogus.com not found')
        action = models.Action.objects.get(name='send json report')

        now = datetime.now(pytz.timezone(settings.TIME_ZONE))
        scheduled_item = models.ScheduledOperation(
            user=user,
            operation_type=models.Log.ACTION_RUN_JSON_REPORT,
            name='JSON Report scheduled action',
            workflow=action.workflow,
            action=action,
            execute=now + timedelta(minutes=2),
            status=models.scheduler.STATUS_PENDING,
            payload={'token': token})
        scheduled_item.save()

        # Execute the scheduler
        tasks.execute_scheduled_operation(scheduled_item.id)

        json_outbox = OnTaskSharedState.json_outbox
        scheduled_item.refresh_from_db()
        assert scheduled_item.status == models.scheduler.STATUS_DONE
        assert len(json_outbox) == 1
        assert all(token in item['auth'] for item in json_outbox) 
Example #19
Source File: test_scheduled_actions.py    From ontask_b with MIT License 5 votes vote down vote up
def test_scheduled_email_report(self):
        """Create a scheduled send report action and execute it."""

        user = get_user_model().objects.get(email='instructor01@bogus.com')

        # User must exist
        self.assertIsNotNone(user, 'User instructor01@bogus.com not found')
        action = models.Action.objects.get(name='send list')

        now = datetime.now(pytz.timezone(settings.TIME_ZONE))
        scheduled_item = models.ScheduledOperation(
            user=user,
            operation_type=models.Log.ACTION_RUN_EMAIL_REPORT,
            name='send list scheduled action',
            workflow=action.workflow,
            action=action,
            execute=now + self.tdelta,
            status=models.scheduler.STATUS_PENDING,
            payload={
                'email_to': 'recipient@bogus.com',
                'subject': 'Action subject',
                'cc_email': '',
                'bcc_email': ''})
        scheduled_item.save()

        # Execute the scheduler
        tasks.execute_scheduled_operation(scheduled_item.id)

        scheduled_item.refresh_from_db()
        assert scheduled_item.status == models.scheduler.STATUS_DONE
        assert len(mail.outbox) == 1
        assert('student01@bogus.com' in mail.outbox[0].body)
        assert('student03@bogus.com' in mail.outbox[0].body) 
Example #20
Source File: test_scheduled_actions.py    From ontask_b with MIT License 5 votes vote down vote up
def test_scheduled_json_action(self):
        """Create a scheduled send list action and execute it."""
        token = 'fake token'

        OnTaskSharedState.json_outbox = []
        settings.EXECUTE_ACTION_JSON_TRANSFER = False

        user = get_user_model().objects.get(email='instructor01@bogus.com')

        # User must exist
        self.assertIsNotNone(user, 'User instructor01@bogus.com not found')
        action = models.Action.objects.get(name='send json')

        now = datetime.now(pytz.timezone(settings.TIME_ZONE))
        scheduled_item = models.ScheduledOperation(
            user=user,
            operation_type=models.Log.ACTION_RUN_PERSONALIZED_JSON,
            name='JSON scheduled action',
            workflow=action.workflow,
            action=action,
            execute=now + self.tdelta,
            status=models.scheduler.STATUS_PENDING,
            payload={
                'item_column': action.workflow.columns.get(name='email').id,
                'token': token})
        scheduled_item.save()

        # Execute the scheduler
        tasks.execute_scheduled_operation(scheduled_item.id)

        scheduled_item.refresh_from_db()
        json_outbox = OnTaskSharedState.json_outbox
        assert scheduled_item.status == models.scheduler.STATUS_DONE
        assert len(json_outbox) == 3
        assert all(item['target'] == action.target_url for item in json_outbox)
        assert all(token in item['auth'] for item in json_outbox) 
Example #21
Source File: action.py    From ontask_b with MIT License 5 votes vote down vote up
def is_active(self) -> bool:
        """Calculate if the action is ready for execution.

        Function to ask if an action is active: the current time is within the
        interval defined by active_from - active_to.
        :return: Boolean encoding the active status
        """
        now = datetime.datetime.now(pytz.timezone(settings.TIME_ZONE))
        return not (
            (self.active_from and now < self.active_from)
            or (self.active_to and self.active_to < now)) 
Example #22
Source File: models.py    From mrs with GNU Affero General Public License v3.0 5 votes vote down vote up
def creation_date_normalized(self):
        return pytz.timezone(settings.TIME_ZONE).normalize(
            self.creation_datetime).strftime('%d/%m/%Y') 
Example #23
Source File: models.py    From mrs with GNU Affero General Public License v3.0 5 votes vote down vote up
def creation_day_time(self):
        # french calendar date and tz time for creation_datetime
        return self.creation_datetime.astimezone(
            pytz.timezone(settings.TIME_ZONE)
        ) 
Example #24
Source File: models.py    From mrs with GNU Affero General Public License v3.0 5 votes vote down vote up
def delay(self):
        if not self.mandate_date:
            return
        mandate_datetime = datetime.datetime(
            self.mandate_date.year,
            self.mandate_date.month,
            self.mandate_date.day,
            0,
            tzinfo=pytz.timezone(settings.TIME_ZONE),
        )
        delta = mandate_datetime - self.creation_datetime_normalized
        return delta.days + (delta.seconds / 60 / 60 / 24) 
Example #25
Source File: timezone.py    From python with Apache License 2.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 #26
Source File: base.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def check_settings(self):
        if self.settings_dict['TIME_ZONE'] is not None:
            if not settings.USE_TZ:
                raise ImproperlyConfigured(
                    "Connection '%s' cannot set TIME_ZONE because USE_TZ is "
                    "False." % self.alias)
            elif self.features.supports_timezones:
                raise ImproperlyConfigured(
                    "Connection '%s' cannot set TIME_ZONE because its engine "
                    "handles time zones conversions natively." % self.alias) 
Example #27
Source File: base.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def timezone_name(self):
        """
        Name of the time zone of the database connection.
        """
        if not settings.USE_TZ:
            return settings.TIME_ZONE
        elif self.settings_dict['TIME_ZONE'] is None:
            return 'UTC'
        else:
            return self.settings_dict['TIME_ZONE'] 
Example #28
Source File: timezone.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def deactivate():
    """
    Unset 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 #29
Source File: timezone.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def get_default_timezone():
    """
    Return the default time zone as a tzinfo instance.

    This is the time zone defined by settings.TIME_ZONE.
    """
    return pytz.timezone(settings.TIME_ZONE)


# This function exists for consistency with get_current_timezone_name 
Example #30
Source File: search_indexes.py    From nyc-councilmatic with MIT License 5 votes vote down vote up
def prepare_last_action_date(self, obj):
        app_timezone = pytz.timezone(settings.TIME_ZONE)

        if not obj.last_action_date:
            index_actions = [a.date for a in obj.actions.all()]

            if index_actions:
                index_actions = max(index_actions)

            return index_actions

        return obj.last_action_date