我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.conf.settings.TIME_ZONE。
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: # Only this branch requires pytz. return pytz.timezone(self.settings_dict['TIME_ZONE'])
def pootle_context(request): """Exposes settings to templates.""" # FIXME: maybe we should expose relevant settings only? return { 'settings': { 'POOTLE_TITLE': settings.POOTLE_TITLE, 'POOTLE_INSTANCE_ID': settings.POOTLE_INSTANCE_ID, 'POOTLE_CONTACT_ENABLED': (settings.POOTLE_CONTACT_ENABLED and settings.POOTLE_CONTACT_EMAIL), 'POOTLE_SIGNUP_ENABLED': settings.POOTLE_SIGNUP_ENABLED, 'POOTLE_CACHE_TIMEOUT': settings.POOTLE_CACHE_TIMEOUT, 'TZ': settings.TIME_ZONE, 'TZ_OFFSET': TZ_OFFSET, 'DEBUG': settings.DEBUG, }, 'custom': settings.POOTLE_CUSTOM_TEMPLATE_CONTEXT, '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), 'display_agreement': _agreement_context(request), }
def _select_locale(self, request): supported = request.event.locales if (hasattr(request, 'event') and request.event) else settings.LANGUAGES language = ( self._language_from_user(request, supported) or self._language_from_cookie(request, supported) or self._language_from_browser(request, supported) ) if hasattr(request, 'event') and request.event: language = language or request.event.locale translation.activate(language) request.LANGUAGE_CODE = translation.get_language() with suppress(pytz.UnknownTimeZoneError): if request.user.is_authenticated: tzname = request.user.timezone elif hasattr(request, 'event') and request.event: tzname = request.event.timezone else: tzname = settings.TIME_ZONE timezone.activate(pytz.timezone(tzname)) request.timezone = tzname
def __init__(self, begin=None, end=None): if begin: self.begin = arrow.Arrow.strptime(begin, '%Y-%m-%d', settings.TIME_ZONE) if begin else arrow.now() self.begin = self.begin.floor('day').to('UTC').datetime elif end: to = arrow.Arrow.strptime(end, '%Y-%m-%d', settings.TIME_ZONE).floor('day').to('UTC').datetime self.begin = to - timezone.timedelta(days=settings.EVENTS_CALENDAR_PERIOD) else: self.begin = arrow.now() self.begin = self.begin.floor('day').to('UTC').datetime if end: self.end = arrow.Arrow.strptime(end, '%Y-%m-%d', settings.TIME_ZONE).floor('day').to('UTC').datetime else: self.end = self.begin + timezone.timedelta(days=settings.EVENTS_CALENDAR_PERIOD) self.events = Event.objects.get_by_dates(begin=self.begin, end=self.end)
def test_event_notifications_task(self): """ Test event_notifications_task """ event_notifications_task.delay() self.assertEqual(len(mail.outbox), 2) event = Event.objects.first() self.assertEqual( mail.outbox[0].subject, settings.EMAIL_SUBJECT_PREFIX + 'Upcoming event - ' + event.title) self.assertEqual(mail.outbox[1].subject, settings.EMAIL_SUBJECT_PREFIX + '??????????? ? ??????????? ??????????') self.assertNotEqual(event.notified_at, None) begin = arrow.get(event.begin).to(settings.TIME_ZONE).datetime sms = Sms.objects.first() self.assertTrue(begin.strftime('%d.%m.%Y %H:%M') in sms.text)
def event_notifications_task(): events = Event.objects.get_for_notification() for event in events: Mailer.mail_managers( subject='Upcoming event' + ' - ' + event.title, template='emails/upcoming_event_manager.html', data={'event': event}) client = event.client if client.email: Mailer.mail_user( subject='??????????? ? ??????????? ??????????', template='emails/upcoming_event_client.html', data={'event': event}, email=client.email) if client.phone: sender = Sender() begin = arrow.get(event.begin).to(settings.TIME_ZONE).datetime sender.send_sms( 'Zdravstvuyte. Napominaju Vam, chto u Vas {} zaplanirovana fotosessija. Aleksandra Vishleva +7(903)735-60-96'. format(begin.strftime('%d.%m.%Y %H:%M')), client=client, send_before=begin - timedelta(hours=6)) event.notified_at = timezone.now() event.save()
def xformsManifest(request, username, id_string): xform = get_object_or_404( XForm, id_string__exact=id_string, user__username__iexact=username) formlist_user = xform.user profile, created = \ UserProfile.objects.get_or_create(user=formlist_user) if profile.require_auth: authenticator = HttpDigestAuthenticator() if not authenticator.authenticate(request): return authenticator.build_challenge_response() response = render(request, "xformsManifest.xml", { 'host': request.build_absolute_uri().replace( request.get_full_path(), ''), 'media_files': MetaData.media_upload(xform, download=True) }, content_type="text/xml; charset=utf-8") response['X-OpenRosa-Version'] = '1.0' tz = pytz.timezone(settings.TIME_ZONE) dt = datetime.now(tz).strftime('%a, %d %b %Y %H:%M:%S %Z') response['Date'] = dt return response
def set_asset_user_metadata(instance, user): """ Sets Asset uploaded_by, uploaded_at, last_edit_by, last_edit_at and owner. Called on save by AssetAdmin and FolderAdmin (for AssetInlines). """ # on first save... if not instance.pk: instance.uploaded_by = user instance.uploaded_at = datetime.now(timezone(settings.TIME_ZONE)) # on subsequent saves... else: instance.last_edit_by = user instance.last_edit_at = datetime.now(timezone(settings.TIME_ZONE)) # owner cannot be empty... if not instance.owner: instance.owner = user
def get_fhir_now(my_now=None): """ Format a json datetime in xs:datetime format .now(): 2012-02-17 09:52:35.033232 datetime.datetime.now(pytz.utc).isoformat() '2012-02-17T11:58:44.789024+00:00' """ if my_now: now_is = my_now else: now_is = datetime.now(timezone(settings.TIME_ZONE)) format_now = now_is.isoformat() return format_now
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'])
def reading_timestamp_to_datetime(string): """ Converts a string containing a timestamp to a timezone aware datetime. """ timestamp = re.search(r'(\d{2,2})(\d{2,2})(\d{2,2})(\d{2,2})(\d{2,2})(\d{2,2})([WS])+', string) meter_timestamp = timezone.datetime( year=2000 + int(timestamp.group(1)), month=int(timestamp.group(2)), day=int(timestamp.group(3)), hour=int(timestamp.group(4)), minute=int(timestamp.group(5)), second=int(timestamp.group(6)), ) is_dst = timestamp.group(7) == 'S' local_timezone = pytz.timezone(settings.TIME_ZONE) return local_timezone.localize(meter_timestamp, is_dst=is_dst).astimezone(pytz.utc)
def get_timestamp(filename): class GMLHandler(xml.sax.ContentHandler): timestamp = None def startElement(self, name, attrs): if name == "wfs:FeatureCollection": self.timestamp = attrs['timeStamp'] handler = GMLHandler() parser = xml.sax.make_parser() parser.setContentHandler(handler) parser.parse(filename) timestamp = iso8601.parse_date(handler.timestamp, default_timezone=None) return pytz.timezone(settings.TIME_ZONE).localize(timestamp)
def prepare(self, data): prepped = super(ITSystemEventResource, self).prepare(data) prepped['event_type'] = data.get_event_type_display() # Output times as the local timezone. tz = pytz.timezone(settings.TIME_ZONE) prepped['start'] = data.start.astimezone(tz) if data.end: prepped['end'] = data.end.astimezone(tz) else: prepped['end'] = None if data.duration: prepped['duration_sec'] = data.duration.seconds else: prepped['duration_sec'] = None if data.it_systems: prepped['it_systems'] = [i.name for i in data.it_systems.all()] else: prepped['it_systems'] = None if data.locations: prepped['locations'] = [i.name for i in data.locations.all()] else: prepped['locations'] = None return prepped
def prepare(self, data): """Modify the returned object to append the GAL Department value. """ prepped = super(DepartmentUserResource, self).prepare(data) tz = pytz.timezone(settings.TIME_ZONE) if 'pk' in data: prepped['gal_department'] = DepartmentUser.objects.get(pk=data['pk']).get_gal_department() if 'date_updated' in data and data['date_updated']: prepped['date_updated'] = data['date_updated'].astimezone(tz) if 'date_ad_updated' in data and data['date_ad_updated']: prepped['date_ad_updated'] = data['date_ad_updated'].astimezone(tz) if 'expiry_date' in data and data['expiry_date']: prepped['expiry_date'] = data['expiry_date'].astimezone(tz) if data['expiry_date'] < timezone.now(): data['ad_expired'] = True else: data['ad_expired'] = False return prepped
def xformsManifest(request, username, id_string): xform = get_object_or_404( XForm, id_string__iexact=id_string, user__username__iexact=username) formlist_user = xform.user profile, created = \ UserProfile.objects.get_or_create(user=formlist_user) if profile.require_auth: authenticator = HttpDigestAuthenticator() if not authenticator.authenticate(request): return authenticator.build_challenge_response() response = render(request, "xformsManifest.xml", { 'host': request.build_absolute_uri().replace( request.get_full_path(), ''), 'media_files': MetaData.media_upload(xform, download=True) }, content_type="text/xml; charset=utf-8") response['X-OpenRosa-Version'] = '1.0' tz = pytz.timezone(settings.TIME_ZONE) dt = datetime.now(tz).strftime('%a, %d %b %Y %H:%M:%S %Z') response['Date'] = dt return response
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, '')
def safe_make_aware(value, timezone=None): """Safely call Django's make_aware to get aware datetime. Makes sure DST doesn't cause problems.""" if not timezone: timezone = settings.TIME_ZONE return make_aware(value, is_dst=is_dst(timezone))
def test_execution_in_past(self, mock_run): datawatch.get_all_registered_checks = mock.MagicMock(return_value=[ CheckRunEvery]) scheduler = Scheduler() scheduler.get_last_executions = mock.MagicMock(return_value={ 'django_datawatch.tests.test_scheduler.CheckRunEvery': datetime.datetime(2016, 1, 1, 0, 0, 0, 0, pytz.timezone( settings.TIME_ZONE)), }) scheduler.run_checks() self.assertTrue(mock_run.called)
def test_execution_in_future(self, mock_run): datawatch.get_all_registered_checks = mock.MagicMock(return_value=[ CheckRunEvery]) scheduler = Scheduler() scheduler.get_last_executions = mock.MagicMock(return_value={ 'django_datawatch.tests.test_scheduler.CheckRunEvery': datetime.datetime(2016, 12, 1, 0, 0, 0, 0, pytz.timezone( settings.TIME_ZONE)), }) scheduler.run_checks() self.assertFalse(mock_run.called)
def test_execution_in_future_and_force(self, mock_run): datawatch.get_all_registered_checks = mock.MagicMock(return_value=[ CheckRunEvery]) scheduler = Scheduler() scheduler.get_last_executions = mock.MagicMock(return_value={ 'django_datawatch.tests.test_scheduler.CheckRunEvery': datetime.datetime(2016, 12, 1, 0, 0, 0, 0, pytz.timezone( settings.TIME_ZONE)), }) scheduler.run_checks(force=True) self.assertTrue(mock_run.called)
def as_server_datetime(_datetime): """Localiza la marca de tiempo en función de la zona de tiempo del servidor""" SERVERT_PYTZ = pytz.timezone(settings.TIME_ZONE) return SERVERT_PYTZ.localize(_datetime)
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']
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) elif pytz is None: raise ImproperlyConfigured( "Connection '%s' cannot set TIME_ZONE because pytz isn't " "installed." % self.alias)
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
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
def _deserialize(self, value, attr, data): value = int(value) timezone = pytz.timezone(settings.TIME_ZONE) return datetime.fromtimestamp(value, timezone)
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()
def talk_to_dict(talk): return { 'title': talk.title, 'description': talk.description, 'category': str(talk.category), 'accepted': talk.accepted, 'confirmed': talk.confirmed, 'start_date': talk.start_date.astimezone(tz=pytz.timezone(settings.TIME_ZONE)) if talk.start_date else None, 'duration': talk.estimated_duration, 'track': str(talk.track) if talk.track else '', 'video': talk.video, 'speakers': list(map(speaker_to_dict, talk.speakers.all())), }
def _as_ics(self, citymeo=False): if not self.initialized: self._lazy_init() cal = iCalendar() cal.add('prodid', '-//PonyConf.io//PonyConf//FR') cal.add('version', '2.0') cal.add('x-wr-calname', self.conference.name) cal.add('x-wr-timezone', settings.TIME_ZONE) cal.add('calscale', 'GREGORIAN') talks = self.talks if citymeo and talks.exists(): talks = talks.filter(start_date__gte=now()-timedelta(minutes=5)) if talks.exists(): limit = talks.first().start_date.replace(hour=23, minute=59, second=59) talks = talks.filter(start_date__lte=limit) for talk in talks: event = iEvent() event.add('dtstart', talk.start_date) if not talk.end_date: continue event.add('dtend', talk.end_date) event.add('dtstamp', talk.updated) event.add('summary', talk.title) if talk.room: event.add('location', talk.room) event.add('status', 'CONFIRMED' if talk.accepted else 'TENTATIVE') if not citymeo: event.add('description', talk.description) event.add('uid', '%s/%s' % (self.site.domain, talk.id)) cal.add_component(event) return cal.to_ical()
def handle(self, *args, **options): SKIP_FIELDS = None #set(['n_tweets', 'diffusion', 'reply']) TIME_BUCKET_SIZE = options.get('time_bucket', 60) S = options.get('size', 100) HOURS = options.get('hours', 2) print(Tweet.objects.aggregate(maxdate=Max('datetime'))) TIME_RANGE = [Tweet.objects.aggregate(maxdate=Max('datetime'))['maxdate'] - timedelta(hours=HOURS), Tweet.objects.aggregate(maxdate=Max('datetime'))['maxdate']] TURNS = options.get('turns', 5) TIME_ZONE = pytz.timezone(options.get('time_zone', settings.TIME_ZONE)) EXCLUDE_REPLIES = bool(options.get('exclude_replies', True)) EXCLUDE_RETWEETS = bool(options.get('exclude_retweets', False)) INFORMATIONAL_ONLY = bool(options.get('informational_only', True)) POST_TO_TWITTER = bool(options.get('post_timeline', False)) UPDATE_USERS = bool(options.get('update_users', False)) POPULAR_ONLY = bool(options.get('popular', False)) print(SKIP_FIELDS) print(TIME_BUCKET_SIZE) print(S) print(TIME_RANGE) print(TIME_ZONE) print(EXCLUDE_REPLIES, EXCLUDE_RETWEETS) print(INFORMATIONAL_ONLY) print(HOURS) print(POST_TO_TWITTER) print(UPDATE_USERS) api_keys = settings.TWITTER_USER_KEYS auth = tweepy.OAuthHandler(api_keys['consumer_key'], api_keys['consumer_secret']) auth.set_access_token(api_keys['access_token_key'], api_keys['access_token_secret']) api = tweepy.API(auth) generate_timeline(TIME_RANGE, skip_fields=SKIP_FIELDS, size=S, sideline_turns=TURNS, time_bucket_size=TIME_BUCKET_SIZE, time_zone=TIME_ZONE, twitter_api=api, exclude_replies=EXCLUDE_REPLIES, exclude_retweets=EXCLUDE_RETWEETS, informational_only=INFORMATIONAL_ONLY, update_users=UPDATE_USERS, post_to_twitter=POST_TO_TWITTER, retweeted_only=POPULAR_ONLY, n_candidates=options.get('n_candidates', None))
def test_time_zone(self): response = self.client.get(reverse('deviceinfo'), format="json") self.assertTrue(response.data['server_timezone'], settings.TIME_ZONE)
def get(self, request, format=None): info = {} info['version'] = kolibri.__version__ status, urls = get_urls() if not urls: # Will not return anything when running the debug server, so at least return the current URL urls = [request.build_absolute_uri('/')] filtered_urls = [url for url in urls if '127.0.0.1' not in url and 'localhost' not in url] if filtered_urls: urls = filtered_urls info['urls'] = urls if settings.DATABASES['default']['ENGINE'].endswith('sqlite3'): # If any other database backend, will not be file backed, so no database path to return info['database_path'] = settings.DATABASES['default']['NAME'] instance_model = InstanceIDModel.get_or_create_current_instance()[0] info['device_name'] = instance_model.hostname info['device_id'] = instance_model.id info['os'] = instance_model.platform info['content_storage_free_space'] = get_free_space() # This returns the localized time for the server info['server_time'] = local_now() # Returns the named timezone for the server (the time above only includes the offset) info['server_timezone'] = settings.TIME_ZONE return Response(info)
def get_for_closing(self, date=None): """ :param date: close from date :type date: datetime.datetime :return: Events :rtype: queryset """ date = arrow.Arrow.strptime( date, '%Y-%m-%d', settings.TIME_ZONE) if date else arrow.now() date = date.floor('day').to('UTC').datetime queryset = self.get_queryset() return queryset.filter( end__lt=date, paid__gte=F('total')).exclude(status='closed')
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
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 }
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
def test_get_not_utc(self): self.assertEqual(settings.TIME_ZONE, 'America/Toronto') self.test_get()
def process_request(self, request): tz = request.session.get(settings.TIMEZONE_SESSION_KEY) if not tz: tz = settings.TIME_ZONE timezone.activate(tz)
def time_settings(self, is_dst): this_is_dst = is_dst if settings.USE_TZ: tz_setting = settings.TIME_ZONE this_timezone = tz_setting else: this_timezone = 'Europe/Helsinki' return this_is_dst, this_timezone
def datetime_to_utc(date): local = pytz.timezone(settings.TIME_ZONE) local_dt = local.localize(date, is_dst=None) return local_dt.astimezone(pytz.utc)
def check_tg(self, options): tg_name1 = options['talkgroup1'] tg_name2 = options['talkgroup2'] try: tg1 = TalkGroup.objects.get(slug=tg_name1) except TalkGroup.DoesNotExist: self.stdout.write(self.style.ERROR('Talk Group {} does not exist, make sure you are using the slug name'.format(tg_name1))) sys.exit(2) try: tg2 = TalkGroup.objects.get(slug=tg_name2) except TalkGroup.DoesNotExist: self.stdout.write(self.style.ERROR('Talk Group {} does not exist, make sure you are using the slug name'.format(tg_name2))) sys.exit(3) last_tg1 = Transmission.objects.filter(talkgroup_info=tg1)[0] last_tg2 = Transmission.objects.filter(talkgroup_info=tg2)[0] local_tz = pytz.timezone(settings.TIME_ZONE) settings_time_zone = local_tz time1 = last_tg1.start_datetime.astimezone(local_tz) time2 = last_tg2.start_datetime.astimezone(local_tz) if time1 >= time2: time_diff = time1 - time2 else: time_diff = time2 - time1 max_diff = timezone.timedelta(minutes=options['minutes']) self.stdout.write('Comparing Last Transmission {} {} to {} {} ({})'.format(tg1, time1, tg2, time2, time_diff)) if time_diff > max_diff: self.stdout.write(self.style.ERROR('Too long between simulcast transmissions {}'.format(time_diff))) sys.exit(1) else: self.stdout.write(self.style.SUCCESS('Good'))