我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.utils.timezone.make_naive()。
def adapt_datetimefield_value(self, value): """ Transform a datetime value to an object compatible with what is expected by the backend driver for datetime columns. If naive datetime is passed assumes that is in UTC. Normally Django models.DateTimeField makes sure that if USE_TZ is True passed datetime is timezone aware. """ if value is None: return None # cx_Oracle doesn't support tz-aware datetimes if timezone.is_aware(value): if settings.USE_TZ: value = timezone.make_naive(value, self.connection.timezone) else: raise ValueError("Oracle backend does not support timezone-aware datetimes when USE_TZ is False.") return Oracle_datetime.from_datetime(value)
def get(self, request, *args, **kwargs): export = request.GET.get('export') if export == 'true': query_set = self._get_query_set() headers = ('??????', '??', '???', '????', '????', '????', '???', '??',) columns = (lambda x: timezone.make_naive(x.submit_time), 'account.user.teacher.name', 'account.user.profile.phone', lambda x: (x.abs_amount/100), 'withdrawal.bankcard.bank_name', 'withdrawal.bankcard.card_number', 'withdrawal.bankcard.opening_bank', 'withdrawal.get_status_display', ) return excel.excel_response(query_set, columns, headers, '????????.xls') return super(TeacherWithdrawalView, self).get(request, *args, **kwargs)
def allDayForDate(self,this_date,timeZone=None): ''' This method determines whether the occurrence lasts the entirety of a specified day in the specified time zone. If no time zone is specified, then it uses the default time zone). Also, give a grace period of a few minutes to account for issues with the way events are sometimes entered. ''' if isinstance(this_date,datetime): d = this_date.date() else: d = this_date date_start = datetime(d.year,d.month,d.day) naive_start = self.startTime if timezone.is_naive(self.startTime) else timezone.make_naive(self.startTime, timezone=timeZone) naive_end = self.endTime if timezone.is_naive(self.endTime) else timezone.make_naive(self.endTime, timezone=timeZone) return ( # Ensure that all comparisons are done in local time naive_start <= date_start and naive_end >= date_start + timedelta(days=1,minutes=-30) )
def adapt_datetimefield_value(self, value): if value is None: return None # Expression values are adapted by the database. if hasattr(value, 'resolve_expression'): return value # MySQL doesn't support tz-aware datetimes if timezone.is_aware(value): if settings.USE_TZ: value = timezone.make_naive(value, self.connection.timezone) else: raise ValueError("MySQL backend does not support timezone-aware datetimes when USE_TZ is False.") if not self.connection.features.supports_microsecond_precision: value = value.replace(microsecond=0) return six.text_type(value)
def adapt_datetimefield_value(self, value): """ Transform a datetime value to an object compatible with what is expected by the backend driver for datetime columns. If naive datetime is passed assumes that is in UTC. Normally Django models.DateTimeField makes sure that if USE_TZ is True passed datetime is timezone aware. """ if value is None: return None # Expression values are adapted by the database. if hasattr(value, 'resolve_expression'): return value # cx_Oracle doesn't support tz-aware datetimes if timezone.is_aware(value): if settings.USE_TZ: value = timezone.make_naive(value, self.connection.timezone) else: raise ValueError("Oracle backend does not support timezone-aware datetimes when USE_TZ is False.") return Oracle_datetime.from_datetime(value)
def adapt_datetimefield_value(self, value): if value is None: return None # Expression values are adapted by the database. if hasattr(value, 'resolve_expression'): return value # SQLite doesn't support tz-aware datetimes if timezone.is_aware(value): if settings.USE_TZ: value = timezone.make_naive(value, self.connection.timezone) else: raise ValueError("SQLite backend does not support timezone-aware datetimes when USE_TZ is False.") return six.text_type(value)
def get_start_date(self, qs): most_recent_kwargs = self.get_most_recent_kwargs() last_stat = self.statistic_model.objects.most_recent( **most_recent_kwargs) if last_stat: start_date = last_stat.date else: first_instance = qs.order_by(self.date_field).first() if first_instance is None: # No data return start_date = getattr(first_instance, self.date_field) if start_date and isinstance(start_date, datetime): if timezone.is_aware(start_date): start_date = timezone.make_naive(start_date).date() else: start_date = start_date.date() return start_date
def summarize(self, start, end): if not api.nova.extension_supported('SimpleTenantUsage', self.request): return if start <= end and start <= self.today: # The API can't handle timezone aware datetime, so convert back # to naive UTC just for this last step. start = timezone.make_naive(start, timezone.utc) end = timezone.make_naive(end, timezone.utc) try: self.usage_list = self.get_usage_list(start, end) except Exception: exceptions.handle(self.request, _('Unable to retrieve usage information.')) elif end < start: messages.error(self.request, _("Invalid time period. The end date should be " "more recent than the start date.")) elif start > self.today: messages.error(self.request, _("Invalid time period. You are requesting " "data from the future which may not exist.")) for project_usage in self.usage_list: project_summary = project_usage.get_summary() for key, value in project_summary.items(): self.summary.setdefault(key, 0) self.summary[key] += value
def to_current_timezone(value): """ When time zone support is enabled, convert aware datetimes to naive datetimes in the current time zone for display. """ if settings.USE_TZ and value is not None and timezone.is_aware(value): current_timezone = timezone.get_current_timezone() return timezone.make_naive(value, current_timezone) return value
def set_cookie(self, key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False): """ Sets a cookie. ``expires`` can be: - a string in the correct format, - a naive ``datetime.datetime`` object in UTC, - an aware ``datetime.datetime`` object in any time zone. If it is a ``datetime.datetime`` object then ``max_age`` will be calculated. """ value = force_str(value) self.cookies[key] = value if expires is not None: if isinstance(expires, datetime.datetime): if timezone.is_aware(expires): expires = timezone.make_naive(expires, timezone.utc) delta = expires - expires.utcnow() # Add one second so the date matches exactly (a fraction of # time gets lost between converting to a timedelta and # then the date string). delta = delta + datetime.timedelta(seconds=1) # Just set max_age - the max_age logic will set expires. expires = None max_age = max(0, delta.days * 86400 + delta.seconds) else: self.cookies[key]['expires'] = expires if max_age is not None: self.cookies[key]['max-age'] = max_age # IE requires expires, so set it if hasn't been already. if not expires: self.cookies[key]['expires'] = cookie_date(time.time() + max_age) if path is not None: self.cookies[key]['path'] = path if domain is not None: self.cookies[key]['domain'] = domain if secure: self.cookies[key]['secure'] = True if httponly: self.cookies[key]['httponly'] = True
def adapt_datetimefield_value(self, value): if value is None: return None # MySQL doesn't support tz-aware datetimes if timezone.is_aware(value): if settings.USE_TZ: value = timezone.make_naive(value, self.connection.timezone) else: raise ValueError("MySQL backend does not support timezone-aware datetimes when USE_TZ is False.") if not self.connection.features.supports_microsecond_precision: value = value.replace(microsecond=0) return six.text_type(value)
def adapt_datetimefield_value(self, value): if value is None: return None # SQLite doesn't support tz-aware datetimes if timezone.is_aware(value): if settings.USE_TZ: value = timezone.make_naive(value, self.connection.timezone) else: raise ValueError("SQLite backend does not support timezone-aware datetimes when USE_TZ is False.") return six.text_type(value)
def to_python(self, value): if value is None: return value if isinstance(value, datetime.datetime): if settings.USE_TZ and timezone.is_aware(value): # Convert aware datetimes to the default time zone # before casting them to dates (#17742). default_timezone = timezone.get_default_timezone() value = timezone.make_naive(value, default_timezone) return value.date() if isinstance(value, datetime.date): return value try: parsed = parse_date(value) if parsed is not None: return parsed except ValueError: raise exceptions.ValidationError( self.error_messages['invalid_date'], code='invalid_date', params={'value': value}, ) raise exceptions.ValidationError( self.error_messages['invalid'], code='invalid', params={'value': value}, )
def make_naive(value, tz=None): """Makes a `datetime` naive, i.e. not aware of timezones. :param value: `datetime` object to make timezone-aware. :param tz: `tzinfo` object with the timezone information the given value needs to be converted to. By default, site's own default timezone will be used. """ if getattr(settings, 'USE_TZ', False) and timezone.is_aware(value): use_tz = tz if tz is not None else timezone.get_default_timezone() value = timezone.make_naive(value, timezone=use_tz) return value
def correct_awareness(value): """Fix the given datetime timezone awareness.""" if isinstance(value, datetime): if settings.USE_TZ: return make_aware(value) elif timezone.is_aware(value): default_tz = timezone.get_default_timezone() return timezone.make_naive(value, default_tz) return value
def enforce_timezone(self, value): """ When `self.default_timezone` is `None`, always return naive datetimes. When `self.default_timezone` is not `None`, always return aware datetimes. """ field_timezone = getattr(self, 'timezone', self.default_timezone()) if (field_timezone is not None) and not timezone.is_aware(value): try: return timezone.make_aware(value, field_timezone) except InvalidTimeError: self.fail('make_aware', timezone=field_timezone) elif (field_timezone is None) and timezone.is_aware(value): return timezone.make_naive(value, utc) return value
def _normalize_timezone_to_utc(self, point_in_time, tzinfo): if point_in_time.tzinfo is not None: return point_in_time.astimezone(pytz.utc) if tzinfo is not None: return tzinfo.localize(point_in_time).astimezone(pytz.utc) if settings.USE_TZ: return pytz.utc.localize(point_in_time) else: if timezone.is_aware(point_in_time): return timezone.make_naive(point_in_time, pytz.utc) else: return point_in_time
def _datetimefield_serializer(pb_obj, pb_field, dj_field_value): """ handling Django DateTimeField field :param pb_obj: protobuf message obj which is return value of to_pb() :param pb_field: protobuf message field which is current processing field :param dj_field_value: Currently proecessing django field value :returns: None """ if getattr(getattr(pb_obj, pb_field.name), 'FromDatetime', False): if settings.USE_TZ: dj_field_value = timezone.make_naive( dj_field_value, timezone=timezone.utc) getattr(pb_obj, pb_field.name).FromDatetime(dj_field_value)
def to_current_timezone(value): """ When time zone support is enabled, convert aware datetimes to naive dateimes in the current time zone for display. """ if settings.USE_TZ and value is not None and timezone.is_aware(value): current_timezone = timezone.get_current_timezone() return timezone.make_naive(value, current_timezone) return value
def ensure_timezone(dateTime,timeZone=None): ''' Since this project is designed to be used in both time-zone aware and naive environments, this utility just returns a datetime as either aware or naive depending on whether time zone support is enabled. ''' if is_aware(dateTime) and not getattr(settings,'USE_TZ',False): return make_naive(dateTime,timezone=timeZone) if is_naive(dateTime) and getattr(settings,'USE_TZ',False): return make_aware(dateTime,timezone=timeZone) # If neither condition is met, then we can return what was passed return dateTime
def ensure_localtime(dateTime): if not getattr(settings,'USE_TZ',False): return make_naive(dateTime) if is_aware(dateTime) else dateTime else: return localtime(make_aware(dateTime) if is_naive(dateTime) else dateTime)
def enforce_timezone(self, value): """ When `self.default_timezone` is `None`, always return naive datetimes. When `self.default_timezone` is not `None`, always return aware datetimes. """ field_timezone = getattr(self, 'timezone', self.default_timezone()) if (field_timezone is not None) and not timezone.is_aware(value): return timezone.make_aware(value, field_timezone) elif (field_timezone is None) and timezone.is_aware(value): return timezone.make_naive(value, timezone.UTC()) return value
def from_native(self, value): if value in validators.EMPTY_VALUES: return None if isinstance(value, datetime.datetime): if timezone and settings.USE_TZ and timezone.is_aware(value): # Convert aware datetimes to the default time zone # before casting them to dates (#17742). default_timezone = timezone.get_default_timezone() value = timezone.make_naive(value, default_timezone) return value.date() if isinstance(value, datetime.date): return value for fmt in self.input_formats: if fmt.lower() == ISO_8601: try: parsed = parse_date(value) except (ValueError, TypeError): pass else: if parsed is not None: return parsed else: try: parsed = datetime.datetime.strptime(value, fmt) except (ValueError, TypeError): pass else: return parsed.date() msg = self.error_messages['invalid'] % readable_date_formats(self.input_formats) raise ValidationError(msg)
def get_or_create_session_id(self, user_id): session_mapping = get_object_or_None(SessionLookup, user_id=user_id) # if its missing create a new one. if session_mapping is None: session_mapping = SessionLookup.objects.create( user_id=user_id, session_id=generate_session_id() ) else: session = ussd_session(session_mapping.session_id) # get last time session was updated if session.get(ussd_airflow_variables.last_update): last_updated = utilities.string_to_datetime( session[ussd_airflow_variables.last_update]) else: last_updated = timezone.make_naive(session_mapping.updated_at) # check inactivity or if session has been closed inactivity_duration = (datetime.now() - last_updated).total_seconds() if inactivity_duration > self.expiry or \ session.get(ussd_airflow_variables.expiry): # update session_mapping with the new session_id session_mapping.session_id = generate_session_id() session_mapping.save() return session_mapping.session_id
def test_csv_okay(self): """ Export tags as CSV. """ _sign_in(self.admin) url = reverse( 'export:tags', kwargs={"project_id": self.project.pk}) resp = self.client.post(url) self.assertEqual(200, resp.status_code) tags = list(read_csv_to_dict(resp.content, encoding='utf-16')) self.assertEqual(2, len(tags)) tag1 = next(t for t in tags if long(t['id']) == self.tag1.pk) self.assertEqual(self.tag1.name, tag1['name']) self.assertEqual(str(self.tag1.description or ''), tag1['description']) self.assertEqual(str(self.tag1.image_url or ''), tag1['image_url']) self.assertEqual( timezone.make_naive( self.tag1.created, timezone.utc ).strftime("%Y-%m-%d %H:%M:%S+00:00"), datetime.datetime.strptime(tag1['created'], '%Y-%m-%d %H:%M:%S.%f+00:00').strftime("%Y-%m-%d %H:%M:%S+00:00")) self.assertEqual( timezone.make_naive( self.tag1.modified, timezone.utc ).strftime("%Y-%m-%d %H:%M:%S+00:00"), datetime.datetime.strptime(tag1['modified'], '%Y-%m-%d %H:%M:%S.%f+00:00').strftime("%Y-%m-%d %H:%M:%S+00:00")) self.assertEqual('2', tag1['instance_count']) self.assertEqual('', tag1['parent_id'])
def from_instance(cls, project): """ Factory method for creating a project document from a Project model instance. """ doc = cls(doc_id=str(project.pk)) copy_attrs = ['name', 'description'] for attr in copy_attrs: setattr(doc, attr, getattr(project, attr, None)) doc.id = unicode(project.pk) # make datetimes timezone naive as appengine doesnt support # indexing aware datetime objects which is annoying doc.created = timezone.make_naive(project.created, timezone.utc) doc.modified = timezone.make_naive(project.modified, timezone.utc) # manually add data that we cant directly copy from the instance if project.owner: doc.owner_id = unicode(project.owner.id) doc.owner_name = '%s %s' % ( project.owner.first_name, project.owner.last_name) # add assigned users doc.assigned_users = ' '.join( str(user_id) for user_id in project.projectusers.filter( is_pending=False, is_assigned=True).values_list( 'user_id', flat=True)).strip() # build ngrams doc.n_grams = cls.make_ngrams(project.name) # return completed doc. return doc
def to_tuple(self): return self.pk, int(make_naive(self.datetime).timestamp())
def cache_key(self): return self.build_cache_key(self.pk, int(make_naive(self.datetime).timestamp()))
def last_update_cache_key(self): last_update = self.created if self.last_update_id is None else self.last_update.datetime return int_to_base36(self.last_update_id or 0)+'_'+int_to_base36(int(make_naive(last_update).timestamp()))