本文整理匯總了Python中django.utils.timezone.get_current_timezone方法的典型用法代碼示例。如果您正苦於以下問題:Python timezone.get_current_timezone方法的具體用法?Python timezone.get_current_timezone怎麽用?Python timezone.get_current_timezone使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類django.utils.timezone
的用法示例。
在下文中一共展示了timezone.get_current_timezone方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: setUp
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import get_current_timezone [as 別名]
def setUp(self):
self.viewset_class = DescriptorSchemaViewSet
super().setUp()
tzone = get_current_timezone()
self.ds1 = DescriptorSchema.objects.create(
contributor=self.user, slug="slug1", name="ds1"
)
self.ds1.created = datetime.datetime(2015, 7, 28, 11, 57, tzinfo=tzone)
self.ds1.save()
self.ds2 = DescriptorSchema.objects.create(
contributor=self.user, slug="slug2", name="ds2"
)
self.ds2.created = datetime.datetime(2016, 8, 29, 12, 58, 0, tzinfo=tzone)
self.ds2.save()
self.ds3 = DescriptorSchema.objects.create(
contributor=self.admin, slug="slug3", name="ds3"
)
self.ds3.created = datetime.datetime(2017, 9, 30, 13, 59, 0, tzinfo=tzone)
self.ds3.save()
示例2: test_lookup_expressions_exact
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import get_current_timezone [as 別名]
def test_lookup_expressions_exact(self):
from .test_app.models import TestModel
tzone = get_current_timezone()
TestModel.objects.create(
name="Object name 4",
number=45,
date=datetime.datetime(2016, 1, 1, 0, 0, tzinfo=tzone),
field_process_type="foo:bar:moo:",
)
response = self._make_request(field_process_type="foo:bar")
self.assertEqual(len(response.data), 1)
self.assertEqual(response.data[0]["name"], "Object name 4")
response = self._make_request(field_process_type__exact="foo:bar")
self.assertEqual(len(response.data), 0)
response = self._make_request(field_process_type__exact="foo:bar:moo:")
self.assertEqual(len(response.data), 1)
self.assertEqual(response.data[0]["name"], "Object name 4")
示例3: from_current_timezone
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import get_current_timezone [as 別名]
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
示例4: get_current_timezone_tag
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import get_current_timezone [as 別名]
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])
示例5: datetimes
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import get_current_timezone [as 別名]
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')
示例6: update_top_stories
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import get_current_timezone [as 別名]
def update_top_stories(self):
try:
posts = self.client.get_top_posts()
today = timezone.now()
for post in posts:
code = post['slug']
story, created = Story.objects.get_or_create(
service=self.service,
code=code,
date=timezone.datetime(today.year, today.month, today.day, tzinfo=timezone.get_current_timezone())
)
if created:
story.title = post['name']
story.description = post['tagline']
story.url = u'{0}{1}'.format(self.service.story_url, code)
story.score = post['votes_count']
story.comments = post['comments_count']
story.status = Story.OK
story.save()
except Exception:
logger.exception('An error occurred while executing `update_top_stores` for Product Hunt.')
raise
示例7: from_current_timezone
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import get_current_timezone [as 別名]
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 as exc:
raise ValidationError(
_('%(datetime)s couldn\'t be interpreted '
'in time zone %(current_timezone)s; it '
'may be ambiguous or it may not exist.'),
code='ambiguous_timezone',
params={'datetime': value, 'current_timezone': current_timezone}
) from exc
return value
示例8: get_current_timezone_tag
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import get_current_timezone [as 別名]
def get_current_timezone_tag(parser, token):
"""
Store 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])
示例9: datetimes
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import get_current_timezone [as 別名]
def datetimes(self, field_name, kind, order='ASC', tzinfo=None):
"""
Return 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')
示例10: clean_expires_at
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import get_current_timezone [as 別名]
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
示例11: parse_date
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import get_current_timezone [as 別名]
def parse_date(date_string, is_iso):
""" Parse a date from a string according to timezone-specific settings
:param date_string: the date string to be parsed
:param is_iso: whether or not to use ISO-specific formatting settings ("%Y-%m-%dT%H:%M:%S" if True, otherwise
"%Y-%m-%d"
:return: a timezone object of the parsed date
"""
if date_string is not None and date_string != "":
if is_iso:
return timezone.make_aware(datetime.strptime(date_string, "%Y-%m-%dT%H:%M:%S"),
timezone.get_current_timezone())
else:
return timezone.make_aware(datetime.strptime(date_string, "%Y-%m-%d"), timezone.get_current_timezone())
else:
print("Returning current datetime as no valid datetime was given")
return timezone.now()
示例12: get_events_users_inbetween
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import get_current_timezone [as 別名]
def get_events_users_inbetween(calendar, since, until):
delta = until - since
result = {}
for i in range(delta.days + 1):
that_day = since + timedelta(days=i)
that_day = timezone.make_aware(that_day, timezone.get_current_timezone())
day = Day(calendar.events.all(), that_day)
for o in day.get_occurrences():
if o.start <= that_day <= o.end:
usernames = o.event.title.split(',')
for username in usernames:
if username not in result.keys():
user_instance = User.objects.get(username=username.strip())
result[username] = {"start": o.start, "person": username.strip(), "end": o.end,
"email": user_instance.email}
else:
result[username]["end"] = o.end
return result.values()
示例13: year_lookup_bounds_for_datetime_field
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import get_current_timezone [as 別名]
def year_lookup_bounds_for_datetime_field(self, value):
"""
Return 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]
示例14: datetimes
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import get_current_timezone [as 別名]
def datetimes(self, field_name, kind, order='ASC', tzinfo=None):
"""
Return a list of datetime objects representing all available
datetimes for the given field_name, scoped to 'kind'.
"""
assert kind in ('year', 'month', 'week', 'day', 'hour', 'minute', 'second'), \
"'kind' must be one of 'year', 'month', 'week', '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')
示例15: test_date_filter
# 需要導入模塊: from django.utils import timezone [as 別名]
# 或者: from django.utils.timezone import get_current_timezone [as 別名]
def test_date_filter(self):
mock = Transaction()
mock.amount = Decimal(10)
mock.description = 'Date Test'
mock.user = User.objects.create_user('hello@test.com')
mock.user.activate_timezone()
mock.timestamp = datetime.datetime(2014, 1, 1, 8, 15, 2, 0, timezone.get_current_timezone())
mock.save()
filter_date = datetime.datetime.combine(datetime.datetime(2014, 1, 1),
datetime.time.max)
actual = Transaction.objects.date(filter_date).first()
self.assertEqual(actual.description, 'Date Test')
filter_date = datetime.datetime(2014, 1, 2, 8, 15, 2, 0, timezone.get_current_timezone())
actual = Transaction.objects.date(filter_date).exists()
self.assertFalse(actual)