我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.utils.timezone.get_current_timezone()。
def setup(self, db, mocker): self.tzinfo = timezone.get_current_timezone() self.subscription_start = datetime( year=2010, month=1, day=24, hour=22, tzinfo=self.tzinfo) self.souvenirs = [ SouvenirFactory(when=datetime(year=i, month=2, day=14, hour=12, tzinfo=self.tzinfo)) for i in range(2010, 2018) ] self.souvenirs.append( SouvenirFactory(when=datetime(year=2015, month=10, day=17, hour=12, tzinfo=self.tzinfo)) ) mocked_now = mocker.patch('souvenirs.reports.timezone.now') mocked_now.return_value = self.now = datetime( year=2017, month=4, day=4, hour=16, tzinfo=self.tzinfo)
def setup(self, db, mocker): self.tzinfo = timezone.get_current_timezone() self.subscription_start = datetime( year=2010, month=1, day=24, hour=22, tzinfo=self.tzinfo) self.souvenirs = [ SouvenirFactory(when=datetime( year=i, month=2, day=14, hour=12, tzinfo=self.tzinfo)) for i in range(2010, 2018) ] self.souvenirs.append( SouvenirFactory(when=datetime(year=2015, month=10, day=17, hour=12, tzinfo=self.tzinfo)) ) mocked_now = mocker.patch('souvenirs.reports.timezone.now') mocked_now.return_value = self.now = datetime( year=2017, month=4, day=3, hour=23, tzinfo=self.tzinfo)
def save(self, *args, **kwargs): if self.date_taken is None: try: exif_date = self.exif.get('DateTimeOriginal', None) if exif_date is not None: d, t = exif_date.split(" ") year, month, day = d.split(':') hour, minute, second = t.split(':') if getattr(settings, "USE_TZ", False): tz = get_current_timezone() self.date_taken = make_aware(datetime( int(year), int(month), int(day), int(hour), int(minute), int(second)), tz) else: self.date_taken = datetime( int(year), int(month), int(day), int(hour), int(minute), int(second)) except Exception: pass if self.date_taken is None: self.date_taken = now() super(Image, self).save(*args, **kwargs)
def from_current_timezone(value): """ When time zone support is enabled, convert naive datetimes entered in the current time zone to aware datetimes. """ if settings.USE_TZ and value is not None and timezone.is_naive(value): current_timezone = timezone.get_current_timezone() try: return timezone.make_aware(value, current_timezone) except Exception: message = _( '%(datetime)s couldn\'t be interpreted ' 'in time zone %(current_timezone)s; it ' 'may be ambiguous or it may not exist.' ) params = {'datetime': value, 'current_timezone': current_timezone} six.reraise(ValidationError, ValidationError( message, code='ambiguous_timezone', params=params, ), sys.exc_info()[2]) return value
def year_lookup_bounds_for_datetime_field(self, value): """ Returns a two-elements list with the lower and upper bound to be used with a BETWEEN operator to query a DateTimeField value using a year lookup. `value` is an int, containing the looked-up year. """ first = datetime.datetime(value, 1, 1) second = datetime.datetime(value, 12, 31, 23, 59, 59, 999999) if settings.USE_TZ: tz = timezone.get_current_timezone() first = timezone.make_aware(first, tz) second = timezone.make_aware(second, tz) first = self.adapt_datetimefield_value(first) second = self.adapt_datetimefield_value(second) return [first, second]
def datetimes(self, field_name, kind, order='ASC', tzinfo=None): """ Returns a list of datetime objects representing all available datetimes for the given field_name, scoped to 'kind'. """ assert kind in ("year", "month", "day", "hour", "minute", "second"), \ "'kind' must be one of 'year', 'month', 'day', 'hour', 'minute' or 'second'." assert order in ('ASC', 'DESC'), \ "'order' must be either 'ASC' or 'DESC'." if settings.USE_TZ: if tzinfo is None: tzinfo = timezone.get_current_timezone() else: tzinfo = None return self.annotate( datetimefield=DateTime(field_name, kind, tzinfo), plain_field=F(field_name) ).values_list( 'datetimefield', flat=True ).distinct().filter(plain_field__isnull=False).order_by(('-' if order == 'DESC' else '') + 'datetimefield')
def get_current_timezone_tag(parser, token): """ Stores the name of the current time zone in the context. Usage:: {% get_current_timezone as TIME_ZONE %} This will fetch the currently active time zone and put its name into the ``TIME_ZONE`` context variable. """ # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments args = token.contents.split() if len(args) != 3 or args[1] != 'as': raise TemplateSyntaxError("'get_current_timezone' requires " "'as variable' (got %r)" % args) return GetCurrentTimezoneNode(args[2])
def checkTime(self, t): """ Returns true if the given datetime t is less then a second different from the current lastTouched value. """ if self.lastTouched is None: return True def make_aware(time): if time.tzinfo is None: return timezone.make_aware( time, timezone.get_current_timezone()) return time self.lastTouched = make_aware(self.lastTouched) t = make_aware(t) return abs(t - self.lastTouched).seconds == 0
def get_qr_image(session: CashdeskSession) -> TemporaryFile: # TODO: check qr code qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=10, border=4, ) tz = timezone.get_current_timezone() data = '{end}\tEinnahme\t{total}\tKassensession\t#{pk}\t{supervisor}\t{user}'.format( end=session.end.astimezone(tz).strftime('%d.%m.%Y\t%H:%M:%S'), total='{0:,.2f}'.format(session.get_cash_transaction_total()).translate(str.maketrans(',.', '.,')), pk=session.pk, supervisor=session.backoffice_user_after.get_full_name(), user=session.user.get_full_name(), ) qr.add_data(data) qr.make() f = TemporaryFile() img = qr.make_image() img.save(f) return f
def create_timezonestamp(value): if value.tzinfo and hasattr(value.tzinfo, 'zone'): # We have a pytz timezone, we can work with this tz = value.tzinfo.zone elif value.tzinfo: # Got some timezone data, but it's not a pytz timezone # Let's just assume someone used dateutil parser on a UTC # ISO format timestamp # Fixes https://github.com/learningequality/kolibri/issues/1824 tz = pytz.utc value = value.astimezone(tz) else: tz = timezone.get_current_timezone().zone value = timezone.make_aware(value, timezone.get_current_timezone()) date_time_string = value.astimezone(pytz.utc).strftime(date_time_format) tz_string = tz_format.format(tz=tz) value = db_storage_string.format(date_time_string=date_time_string, tz_string=tz_string) return value
def timetable_entries_which_violate_constraints(self): start_date = self.start.date() entries_which_violate_constraints = [] for constraint in self.constraints.all(): constraint_start = timezone.make_aware( datetime.combine(start_date, constraint.start_time), timezone.get_current_timezone()) constraint_end = timezone.make_aware( datetime.combine(start_date, constraint.end_time), timezone.get_current_timezone()) participations = Participation.objects.filter(entry__meeting=self, user=constraint.user, ignored_for_optimization=False, entry__timetable_index__isnull=False) for participation in participations: start = participation.entry.start end = participation.entry.end if (constraint_start >= start and constraint_start < end) or \ (constraint_end > start and constraint_end <= end) or \ (constraint_start <= start and constraint_end >= end): entries_which_violate_constraints.append(participation.entry) return entries_which_violate_constraints
def lookups(self, request, admin_view): now = timezone.now() if now.tzinfo is not None: current_tz = timezone.get_current_timezone() now = now.astimezone(current_tz) if hasattr(current_tz, 'normalize'): now = current_tz.normalize(now) today = now.date() #now.replace(hour=0, minute=0, second=0, microsecond=0) tomorrow = today + datetime.timedelta(days=1) return ( (_('??'), {}), (_('Today'), { self.lookup_since_name: str(today), self.lookup_until_name: str(tomorrow), }), )
def clean_expires_at(self): # Validate the expiration date expires_at = self.cleaned_data.get("expires_at", "") never_expires = self.cleaned_data.get("never_expires", "") current_tz = timezone.get_current_timezone() if never_expires: expires_at = None self.cleaned_data["expires_at"] = expires_at if expires_at: # Check if the expiration date is a past date if timezone.localtime(timezone.now(), current_tz) > expires_at: self.add_error('expires_at', _('The date must be on the future.')) if not expires_at and not never_expires: self.add_error('expires_at', _('This field is required, unless box is set to ' 'never expire.')) return expires_at
def datetimes(self, field_name, kind, order='ASC', tzinfo=None): """ Returns a list of datetime objects representing all available datetimes for the given field_name, scoped to 'kind'. """ assert kind in ("year", "month", "day", "hour", "minute", "second"), \ "'kind' must be one of 'year', 'month', 'day', 'hour', 'minute' or 'second'." assert order in ('ASC', 'DESC'), \ "'order' must be either 'ASC' or 'DESC'." if settings.USE_TZ: if tzinfo is None: tzinfo = timezone.get_current_timezone() else: tzinfo = None return self.annotate( datetimefield=Trunc(field_name, kind, output_field=DateTimeField(), tzinfo=tzinfo), plain_field=F(field_name) ).values_list( 'datetimefield', flat=True ).distinct().filter(plain_field__isnull=False).order_by(('-' if order == 'DESC' else '') + 'datetimefield')
def timestamp_for_metadata(dt=None): """ Return a timestamp with a timezone for the configured locale. If all else fails, consider localtime to be UTC. Originally written by Marco Bonetti. """ dt = dt or datetime.datetime.now() if timezone is None: return dt.strftime('%Y-%m-%d %H:%M%z') if not dt.tzinfo: tz = timezone.get_current_timezone() if not tz: tz = timezone.utc dt = dt.replace(tzinfo=timezone.get_current_timezone()) return dt.strftime("%Y-%m-%d %H:%M%z")
def get_display_date(self): tz = timezone.get_current_timezone() start_time = self.start_time.astimezone(tz) end_time = self.end_time.astimezone(tz) if start_time.date() == end_time.date(): date = formats.date_format(start_time, 'DATE_FORMAT') return _("le {date}, de {start_hour} à {end_hour}").format( date=date, start_hour=formats.time_format(start_time, 'TIME_FORMAT'), end_hour=formats.time_format(end_time, 'TIME_FORMAT') ) return _("du {start_date}, {start_time} au {end_date}, {end_time}").format( start_date=formats.date_format(start_time, 'DATE_FORMAT'), start_time=formats.date_format(start_time, 'TIME_FORMAT'), end_date=formats.date_format(end_time, 'DATE_FORMAT'), end_time=formats.date_format(end_time, 'TIME_FORMAT'), )