Here are the examples of the python api django.utils.timezone.make_aware taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
249 Examples
3
Source : operations.py
with GNU General Public License v3.0
from Aghoreshwar
with GNU General Public License v3.0
from Aghoreshwar
def convert_datetimefield_value(self, value, expression, connection):
if value is not None:
if settings.USE_TZ:
value = timezone.make_aware(value, self.connection.timezone)
return value
def convert_uuidfield_value(self, value, expression, connection):
3
Source : operations.py
with GNU General Public License v3.0
from Aghoreshwar
with GNU General Public License v3.0
from Aghoreshwar
def convert_datetimefield_value(self, value, expression, connection):
if value is not None:
if settings.USE_TZ:
value = timezone.make_aware(value, self.connection.timezone)
return value
def convert_datefield_value(self, value, expression, connection):
3
Source : datetime.py
with GNU General Public License v3.0
from Aghoreshwar
with GNU General Public License v3.0
from Aghoreshwar
def convert_value(self, value, expression, connection):
if isinstance(self.output_field, DateTimeField):
if settings.USE_TZ:
if value is None:
raise ValueError(
"Database returned an invalid datetime value. "
"Are time zone definitions for your database installed?"
)
value = value.replace(tzinfo=None)
value = timezone.make_aware(value, self.tzinfo)
elif isinstance(value, datetime):
if isinstance(self.output_field, DateField):
value = value.date()
elif isinstance(self.output_field, TimeField):
value = value.time()
return value
class Trunc(TruncBase):
3
Source : operations.py
with MIT License
from Air-999
with MIT License
from Air-999
def convert_datetimefield_value(self, value, expression, connection):
if value is not None:
value = timezone.make_aware(value, self.connection.timezone)
return value
def convert_uuidfield_value(self, value, expression, connection):
3
Source : operations.py
with MIT License
from Air-999
with MIT License
from Air-999
def convert_datetimefield_value(self, value, expression, connection):
if value is not None:
value = timezone.make_aware(value, self.connection.timezone)
return value
def convert_datefield_value(self, value, expression, connection):
3
Source : dateformat.py
with MIT License
from Air-999
with MIT License
from Air-999
def r(self):
"RFC 5322 formatted date; e.g. 'Thu, 21 Dec 2000 16:01:07 +0200'"
if type(self.data) is datetime.date:
raise TypeError(
"The format for date objects may not contain time-related "
"format specifiers (found 'r')."
)
if is_naive(self.data):
dt = make_aware(self.data, timezone=self.timezone)
else:
dt = self.data
return format_datetime_rfc5322(dt)
def S(self):
3
Source : dates.py
with MIT License
from Air-999
with MIT License
from Air-999
def _make_date_lookup_arg(self, value):
"""
Convert a date into a datetime when the date field is a DateTimeField.
When time zone support is enabled, `date` is assumed to be in the
current time zone, so that displayed items are consistent with the URL.
"""
if self.uses_datetime_field:
value = datetime.datetime.combine(value, datetime.time.min)
if settings.USE_TZ:
value = timezone.make_aware(value)
return value
def _make_single_date_lookup(self, date):
3
Source : test_feedback_request.py
with Mozilla Public License 2.0
from Amsterdam
with Mozilla Public License 2.0
from Amsterdam
def setUp(self):
self.now = make_aware(datetime(2021, 8, 12, 12, 0, 0))
StandardAnswer.objects.all().delete() # Production system has Standard answers via migration, remove for test
StandardAnswerFactory.create(is_visible=True, text='all good', is_satisfied=True, reopens_when_unhappy=False)
StandardAnswerFactory.create(is_visible=False, text='old', is_satisfied=True, reopens_when_unhappy=False)
StandardAnswerFactory.create(is_visible=True, text='not good', is_satisfied=False, reopens_when_unhappy=False)
StandardAnswerFactory.create(is_visible=True, text='never good', is_satisfied=False, reopens_when_unhappy=True)
def test_get_feedback_urls(self):
3
Source : horeca.py
with Mozilla Public License 2.0
from Amsterdam
with Mozilla Public License 2.0
from Amsterdam
def _to_first_and_last_day_of_the_week(isoweek, isoyear):
first_day_of_week = timezone.datetime.strptime(
'{}-W{}-1'.format(isoyear, isoweek), '%G-W%V-%u'
)
first_day_of_week = make_aware(first_day_of_week)
last_day_of_week = first_day_of_week + timedelta(days=7)
return first_day_of_week, last_day_of_week
def _fix_row_to_match_header_count(row, headers):
3
Source : compat.py
with Apache License 2.0
from BeanWei
with Apache License 2.0
from BeanWei
def make_aware(value, timezone, is_dst):
"""is_dst was added for 1.9"""
if django.VERSION >= (1, 9):
return make_aware_orig(value, timezone, is_dst)
else:
return make_aware_orig(value, timezone)
3
Source : financial_annex.py
with GNU Affero General Public License v3.0
from betagouv
with GNU Affero General Public License v3.0
from betagouv
def build_financial_annex_from_number(number):
row = AF_NUMBER_TO_ROW[number]
convention_query = SiaeConvention.objects.filter(asp_id=row.asp_id, kind=row.kind)
if not convention_query.exists():
# There is no point in storing an AF in db if there is no related convention.
return None
return SiaeFinancialAnnex(
number=row.number,
state=row.state,
start_at=timezone.make_aware(row.start_at),
end_at=timezone.make_aware(row.end_date),
convention=convention_query.get(),
)
3
Source : forms.py
with GNU Affero General Public License v3.0
from betagouv
with GNU Affero General Public License v3.0
from betagouv
def clean_start_date(self):
"""
When a start_date does not include time values,
consider that it means "the whole day".
Therefore, start_date time should be 0 am.
"""
start_date = self.cleaned_data.get("start_date")
if start_date:
start_date = datetime.datetime.combine(start_date, datetime.time())
start_date = timezone.make_aware(start_date)
return start_date
def clean_end_date(self):
3
Source : forms.py
with GNU Affero General Public License v3.0
from betagouv
with GNU Affero General Public License v3.0
from betagouv
def clean_end_date(self):
"""
When an end_date does not include time values,
consider that it means "the whole day".
Therefore, end_date time should be 23.59 pm.
"""
end_date = self.cleaned_data.get("end_date")
if end_date:
end_date = datetime.datetime.combine(end_date, datetime.time(hour=23, minute=59, second=59))
end_date = timezone.make_aware(end_date)
return end_date
def get_qs_filters(self):
3
Source : test_account.py
with GNU Affero General Public License v3.0
from chdsbd
with GNU Affero General Public License v3.0
from chdsbd
def test_get_subscription_blocker_trial_expired() -> None:
account = create_account(
trial_expiration=make_aware(datetime.datetime(1900, 2, 13)),
)
assert account.trial_expired() is True
blocker = account.get_subscription_blocker()
assert blocker is not None
assert blocker.kind == "trial_expired"
@pytest.fixture
3
Source : test_account.py
with GNU Affero General Public License v3.0
from chdsbd
with GNU Affero General Public License v3.0
from chdsbd
def test_get_subscription_blocker_seats_exceeded_with_trial(
patched_get_active_users_in_last_30_days: Any,
) -> None:
"""
If an account has active users but is on the trial we should allow them full
access.
"""
account = create_account(
trial_expiration=make_aware(datetime.datetime(2100, 2, 13)),
)
assert account.active_trial() is True
assert (
len(UserPullRequestActivity.get_active_users_in_last_30_days(account=account))
== 5
)
assert account.get_subscription_blocker() is None
def create_account(
3
Source : test_analytics_aggregator.py
with GNU Affero General Public License v3.0
from chdsbd
with GNU Affero General Public License v3.0
from chdsbd
def pull_request_kodiak_updated() -> None:
event = GitHubEvent.objects.create(
event_name="pull_request",
payload=json.load((FIXTURES / "pull_request_kodiak_updated.json").open()),
)
event.created_at = make_aware(datetime.datetime(2020, 2, 13))
event.save()
@pytest.mark.django_db
3
Source : test_pull_request_activity.py
with GNU Affero General Public License v3.0
from chdsbd
with GNU Affero General Public License v3.0
from chdsbd
def pull_request_kodiak_updated() -> None:
event = GitHubEvent.objects.create(
event_name="pull_request",
payload=json.load((FIXTURES / "pull_request_kodiak_updated.json").open()),
)
event.created_at = make_aware(datetime.datetime(2020, 2, 13))
event.save()
@pytest.fixture
3
Source : test_pull_request_activity.py
with GNU Affero General Public License v3.0
from chdsbd
with GNU Affero General Public License v3.0
from chdsbd
def pull_request_kodiak_merged() -> None:
event = GitHubEvent.objects.create(
event_name="pull_request",
payload=json.load((FIXTURES / "pull_request_kodiak_merged.json").open()),
)
event.created_at = make_aware(datetime.datetime(2020, 2, 13))
event.save()
@pytest.fixture
3
Source : test_pull_request_activity.py
with GNU Affero General Public License v3.0
from chdsbd
with GNU Affero General Public License v3.0
from chdsbd
def pull_request_kodiak_approved() -> None:
event = GitHubEvent.objects.create(
event_name="pull_request_review",
# tood fixme installation wrong
payload=json.load(
(FIXTURES / "pull_request_review_kodiak_approved.json").open()
),
)
event.created_at = make_aware(datetime.datetime(2020, 2, 13))
event.save()
@pytest.fixture
3
Source : test_pull_request_activity.py
with GNU Affero General Public License v3.0
from chdsbd
with GNU Affero General Public License v3.0
from chdsbd
def pull_request_total_opened() -> None:
event = GitHubEvent.objects.create(
event_name="pull_request",
payload=json.load((FIXTURES / "pull_request_total_opened.json").open()),
)
event.created_at = make_aware(datetime.datetime(2020, 2, 13))
event.save()
@pytest.fixture
3
Source : test_pull_request_activity.py
with GNU Affero General Public License v3.0
from chdsbd
with GNU Affero General Public License v3.0
from chdsbd
def pull_request_total_merged() -> None:
event = GitHubEvent.objects.create(
event_name="pull_request",
payload=json.load((FIXTURES / "pull_request_total_merged.json").open()),
)
event.created_at = make_aware(datetime.datetime(2020, 2, 13))
event.save()
@pytest.fixture
3
Source : test_pull_request_activity.py
with GNU Affero General Public License v3.0
from chdsbd
with GNU Affero General Public License v3.0
from chdsbd
def pull_request_total_closed() -> None:
event = GitHubEvent.objects.create(
event_name="pull_request",
payload=json.load((FIXTURES / "pull_request_total_closed.json").open()),
)
event.created_at = make_aware(datetime.datetime(2020, 2, 13))
event.save()
@pytest.mark.django_db
3
Source : test_user_pull_request_activity.py
with GNU Affero General Public License v3.0
from chdsbd
with GNU Affero General Public License v3.0
from chdsbd
def pull_request_kodiak_updated_different_institution() -> None:
event = GitHubEvent.objects.create(
event_name="pull_request",
payload=json.load(
(FIXTURES / "pull_request_kodiak_updated_different_institution.json").open()
),
)
event.created_at = make_aware(datetime.datetime(2020, 2, 13))
event.save()
@pytest.fixture
3
Source : test_user_pull_request_activity.py
with GNU Affero General Public License v3.0
from chdsbd
with GNU Affero General Public License v3.0
from chdsbd
def pull_request_total_opened_different_institution() -> None:
event = GitHubEvent.objects.create(
event_name="pull_request",
payload=json.load(
(FIXTURES / "pull_request_total_opened_different_institution.json").open()
),
)
event.created_at = make_aware(datetime.datetime(2020, 2, 13))
event.save()
@pytest.mark.django_db
3
Source : test_user_pull_request_activity.py
with GNU Affero General Public License v3.0
from chdsbd
with GNU Affero General Public License v3.0
from chdsbd
def test_generate_min_progress(
pull_request_total_opened: object,
pull_request_kodiak_updated: object,
pull_request_kodiak_updated_different_institution: object,
pull_request_total_opened_different_institution: object,
) -> None:
UserPullRequestActivityProgress.objects.create(
min_date=make_aware(datetime.datetime(2050, 4, 23))
)
generate_user_activity()
assert UserPullRequestActivityProgress.objects.count() == 2
assert UserPullRequestActivity.objects.count() == 0
def create_user_activity(
3
Source : operations.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def convert_datetimefield_value(self, value, expression, connection, context):
if value is not None:
if settings.USE_TZ:
value = timezone.make_aware(value, self.connection.timezone)
return value
def convert_uuidfield_value(self, value, expression, connection, context):
3
Source : operations.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def convert_datetimefield_value(self, value, expression, connection, context):
if value is not None:
if settings.USE_TZ:
value = timezone.make_aware(value, self.connection.timezone)
return value
def convert_datefield_value(self, value, expression, connection, context):
3
Source : datetime.py
with MIT License
from chunky2808
with MIT License
from chunky2808
def convert_value(self, value, expression, connection, context):
if isinstance(self.output_field, DateTimeField):
if settings.USE_TZ:
if value is None:
raise ValueError(
"Database returned an invalid datetime value. "
"Are time zone definitions for your database installed?"
)
value = value.replace(tzinfo=None)
value = timezone.make_aware(value, self.tzinfo)
elif isinstance(value, datetime):
if isinstance(self.output_field, DateField):
value = value.date()
elif isinstance(self.output_field, TimeField):
value = value.time()
return value
class Trunc(TruncBase):
3
Source : utils.py
with Apache License 2.0
from Code4PuertoRico
with Apache License 2.0
from Code4PuertoRico
def get_fiscal_year_range(fiscal_year):
start_date = timezone.make_aware(datetime.datetime(fiscal_year - 1, 7, 1))
end_date = timezone.make_aware(datetime.datetime(fiscal_year, 6, 30))
return start_date, end_date
def get_chart_data(contracts):
3
Source : validators.py
with MIT License
from craiga
with MIT License
from craiga
def limit_value(self):
"""
Get the latest embargo datetime.
This is the minimum allowable value.
"""
rolls = models.Roll.objects.order_by("-embargo")
try:
return rolls.values_list("embargo", flat=True)[0]
except IndexError:
return timezone.make_aware(datetime.min)
3
Source : jobs.py
with GNU Affero General Public License v3.0
from epilys
with GNU Affero General Public License v3.0
from epilys
def send_digests(job):
now = make_aware(datetime.now())
if job.data:
try:
last_run = make_aware(datetime.fromtimestamp(job.data))
if last_run and (now - last_run) < = timedelta(days=1):
return
except Exception as exc:
print("send_digests() EXC ", exc)
job.data = int(now.timestamp())
job.save()
Digest.send_digests()
def fetch_url(job):
3
Source : models.py
with GNU Affero General Public License v3.0
from epilys
with GNU Affero General Public License v3.0
from epilys
def last_active(self):
with connection.cursor() as cursor:
cursor.execute(
"SELECT last_active FROM taggregation_last_active WHERE taggregation_id = %s",
[self.pk],
)
last_active = cursor.fetchone()
return (
make_aware(datetime.fromisoformat(last_active[0]))
if (last_active and last_active[0])
else None
)
@staticmethod
3
Source : models.py
with GNU Affero General Public License v3.0
from epilys
with GNU Affero General Public License v3.0
from epilys
def last_actives(taggregations):
with connection.cursor() as cursor:
cursor.execute(
f"SELECT MAX(last_active) FROM taggregation_last_active WHERE taggregation_id IN ({','.join([str(t.pk) for t in taggregations])})",
[],
)
last_active = cursor.fetchone()
return (
make_aware(datetime.fromisoformat(last_active[0]))
if (last_active and last_active[0])
else None
)
def last_14_days(self):
3
Source : models.py
with GNU Affero General Public License v3.0
from epilys
with GNU Affero General Public License v3.0
from epilys
def accept(self, user):
self.accepted = make_aware(datetime.now())
self.receiver = user
self.save()
class Vote(models.Model):
3
Source : models.py
with GNU Affero General Public License v3.0
from epilys
with GNU Affero General Public License v3.0
from epilys
def is_new_user(self):
return (make_aware(datetime.now()) - self.created) < timedelta(
days=config.NEW_USER_DAYS
) and not self.is_staff
@cached_property
3
Source : models.py
with GNU Affero General Public License v3.0
from epilys
with GNU Affero General Public License v3.0
from epilys
def latest(user):
with connection.cursor() as cursor:
cursor.execute(
"SELECT MAX(MAX(created), MAX(read)) FROM tade_notification WHERE user_id = %s;",
[user.pk],
)
latest = cursor.fetchone()
return (
make_aware(datetime.fromisoformat(latest[0]))
if (latest and latest[0])
else None
)
class StoryRemoteContent(models.Model):
3
Source : account.py
with GNU Affero General Public License v3.0
from epilys
with GNU Affero General Public License v3.0
from epilys
def notifications(request):
user = request.user
actives = list(user.notifications.filter(read__isnull=True).order_by("-created"))
rest = list(user.notifications.filter(read__isnull=False).order_by("-created"))
user.notifications.filter(read__isnull=True).update(read=make_aware(datetime.now()))
return render(
request,
"account/notifications.html",
{"user": user, "active_notifications": actives, "rest_notifications": rest},
)
@login_required
3
Source : __init__.py
with GNU General Public License v3.0
from esrg-knights
with GNU General Public License v3.0
from esrg-knights
def mock_now(dt=None):
""" Script that changes the default now time to a preset value """
if dt is None:
dt = datetime.datetime(2020, 8, 11, 0, 0)
def adjust_now_time():
return timezone.make_aware(dt)
return adjust_now_time
def mock_is_organiser(result=True):
3
Source : views.py
with GNU General Public License v3.0
from esrg-knights
with GNU General Public License v3.0
from esrg-knights
def get_time_range_data(self):
try:
start_date = datetime.strptime(self.request.GET.get('start-date', ''), self.DATE_TRANSLATION)
start_date = timezone.make_aware(start_date)
except ValueError:
start_date = timezone.now()
end_date = start_date + self.TD_DEFAULT
return start_date, end_date
class LoginRequiredForPostMixin(AccessMixin):
3
Source : utils.py
with GNU General Public License v3.0
from foonsun
with GNU General Public License v3.0
from foonsun
def datetime_combine(date, time):
"""Timezone aware version of `datetime.datetime.combine`"""
return make_aware(
datetime.datetime.combine(date, time), get_current_timezone())
def safe_referrer(request, default):
3
Source : archivehistory.py
with MIT License
from g0v
with MIT License
from g0v
def parse_date(input):
try:
the_date = timezone.make_aware(datetime.strptime(input, '%Y-%m-%d'))
except ValueError:
raise CommandError('Expect date strig format: %Y-%m-%d')
return the_date
def parse_positive_integer(input):
3
Source : customexport.py
with MIT License
from g0v
with MIT License
from g0v
def parse_date(self, input):
try:
return timezone.make_aware(datetime.strptime(input, '%Y%m%d'))
except ValueError:
raise argparse.ArgumentTypeError('Invalid date string: {}'.format(input))
def add_arguments(self, parser):
3
Source : invalidate.py
with MIT License
from g0v
with MIT License
from g0v
def parse_date(date_str):
try:
return timezone.make_aware(datetime.strptime(date_str, '%Y%m%d'))
except ValueError:
raise argparse.ArgumentTypeError('Invalid date string: {}'.format(date_str))
class Command(BaseCommand):
3
Source : export.py
with MIT License
from g0v
with MIT License
from g0v
def parse_date(input):
try:
return timezone.make_aware(datetime.strptime(input, '%Y%m%d'))
except ValueError:
raise argparse.ArgumentTypeError('Invalid date string: {}'.format(input))
arg_parser = argparse.ArgumentParser(description='Export house to csv')
3
Source : funky_time.py
with GNU General Public License v3.0
from GeekZoneHQ
with GNU General Public License v3.0
from GeekZoneHQ
def years_from(years: int, from_date: datetime):
try:
new_date = from_date.replace(year=from_date.year + years)
return make_aware(new_date)
except ValueError:
# Must be 2/29!
new_date = from_date.replace(month=3, day=1, year=from_date.year + years)
return make_aware(new_date)
def is_younger_than(age: int, birth_date: datetime = None):
3
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_datetime_output_field(self):
with register_lookup(models.PositiveIntegerField, DateTimeTransform):
ut = MySQLUnixTimestamp.objects.create(timestamp=time.time())
y2k = timezone.make_aware(datetime(2000, 1, 1))
self.assertSequenceEqual(MySQLUnixTimestamp.objects.filter(timestamp__as_datetime__gt=y2k), [ut])
class YearLteTests(TestCase):
3
Source : test_datetime.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_extract_year_greaterthan_lookup(self):
start_datetime = datetime(2015, 6, 15, 14, 10)
end_datetime = datetime(2016, 6, 15, 14, 10)
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime, is_dst=False)
end_datetime = timezone.make_aware(end_datetime, is_dst=False)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
qs = DTModel.objects.filter(start_datetime__year__gt=2015)
self.assertEqual(qs.count(), 1)
self.assertEqual(str(qs.query).lower().count('extract'), 0)
qs = DTModel.objects.filter(start_datetime__year__gte=2015)
self.assertEqual(qs.count(), 2)
self.assertEqual(str(qs.query).lower().count('extract'), 0)
def test_extract_year_lessthan_lookup(self):
3
Source : test_datetime.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_extract_year_lessthan_lookup(self):
start_datetime = datetime(2015, 6, 15, 14, 10)
end_datetime = datetime(2016, 6, 15, 14, 10)
if settings.USE_TZ:
start_datetime = timezone.make_aware(start_datetime, is_dst=False)
end_datetime = timezone.make_aware(end_datetime, is_dst=False)
self.create_model(start_datetime, end_datetime)
self.create_model(end_datetime, start_datetime)
qs = DTModel.objects.filter(start_datetime__year__lt=2016)
self.assertEqual(qs.count(), 1)
self.assertEqual(str(qs.query).count('extract'), 0)
qs = DTModel.objects.filter(start_datetime__year__lte=2016)
self.assertEqual(qs.count(), 2)
self.assertEqual(str(qs.query).count('extract'), 0)
def test_extract_func(self):
3
Source : test_datetime.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_extract_func_explicit_timezone_priority(self):
start_datetime = microsecond_support(datetime(2015, 6, 15, 23, 30, 1, 321))
end_datetime = microsecond_support(datetime(2015, 6, 16, 13, 11, 27, 123))
start_datetime = timezone.make_aware(start_datetime, is_dst=False)
end_datetime = timezone.make_aware(end_datetime, is_dst=False)
self.create_model(start_datetime, end_datetime)
melb = pytz.timezone('Australia/Melbourne')
with timezone.override(melb):
model = DTModel.objects.annotate(
day_melb=Extract('start_datetime', 'day'),
day_utc=Extract('start_datetime', 'day', tzinfo=timezone.utc),
).order_by('start_datetime').get()
self.assertEqual(model.day_melb, 16)
self.assertEqual(model.day_utc, 15)
def test_trunc_timezone_applied_before_truncation(self):
3
Source : tests.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def test_naive_datetime_conversion(self):
"""
Datetimes are correctly converted to the local time zone.
"""
# Naive date times passed in get converted to the local time zone, so
# check the received zone offset against the local offset.
response = self.client.get('/syndication/naive-dates/')
doc = minidom.parseString(response.content)
updated = doc.getElementsByTagName('updated')[0].firstChild.wholeText
d = Entry.objects.latest('published').published
latest = rfc3339_date(timezone.make_aware(d, TZ))
self.assertEqual(updated, latest)
def test_aware_datetime_conversion(self):
See More Examples