Here are the examples of the python api django.utils.timezone.is_aware taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
98 Examples
4
Example 1
Project: WAPT Source File: fields.py
def _value(self):
date = self.data
if settings.USE_TZ and isinstance(date, datetime.datetime) and timezone.is_aware(date):
self.data = timezone.localtime(date)
return super(DateTimeField, self)._value()
3
Example 2
def adapt_timefield_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):
raise ValueError("SQLite backend does not support timezone-aware times.")
return six.text_type(value)
3
Example 3
Project: django-mysql-pymysql Source File: base.py
def value_to_db_datetime(self, value):
if value is None:
return None
# MySQL doesn't support tz-aware datetimes
if is_aware(value):
if settings.USE_TZ:
value = value.astimezone(utc).replace(tzinfo=None)
else:
raise ValueError("MySQL backend does not support timezone-aware datetimes when USE_TZ is False.")
# MySQL doesn't support microseconds
return text_type(value.replace(microsecond=0))
3
Example 4
Project: django-blog-zinnia Source File: breadcrumbs.py
def entry_breadcrumbs(entry):
"""
Breadcrumbs for an Entry.
"""
date = entry.publication_date
if is_aware(date):
date = localtime(date)
return [year_crumb(date), month_crumb(date),
day_crumb(date), Crumb(entry.title)]
3
Example 5
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)
3
Example 6
def value_to_db_datetime(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 = value.astimezone(timezone.utc).replace(tzinfo=None)
else:
raise ValueError("MySQL backend does not support timezone-aware datetimes when USE_TZ is False.")
return six.text_type(value)
3
Example 7
def adapt_timefield_value(self, value):
"""
Transforms a time value to an object compatible with what is expected
by the backend driver for time columns.
"""
if value is None:
return None
if timezone.is_aware(value):
raise ValueError("Django does not support timezone-aware times.")
return six.text_type(value)
3
Example 8
Project: djangae Source File: utils.py
def make_timezone_naive(value):
if value is None:
return None
if timezone.is_aware(value):
if settings.USE_TZ:
value = value.astimezone(timezone.utc).replace(tzinfo=None)
else:
raise ValueError("Djangae backend does not support timezone-aware datetimes when USE_TZ is False.")
return value
3
Example 9
def U(self):
"Seconds since the Unix epoch (January 1 1970 00:00:00 GMT)"
if isinstance(self.data, datetime.datetime) and is_aware(self.data):
return int(calendar.timegm(self.data.utctimetuple()))
else:
return int(time.mktime(self.data.timetuple()))
3
Example 10
Project: sentry Source File: json.py
def better_default_encoder(o):
if isinstance(o, uuid.UUID):
return o.hex
elif isinstance(o, datetime.datetime):
return o.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
elif isinstance(o, datetime.date):
return o.isoformat()
elif isinstance(o, datetime.time):
if is_aware(o):
raise ValueError("JSON can't represent timezone-aware times.")
r = o.isoformat()
if o.microsecond:
r = r[:12]
return r
elif isinstance(o, (set, frozenset)):
return list(o)
elif isinstance(o, decimal.Decimal):
return six.text_type(o)
raise TypeError(repr(o) + ' is not JSON serializable')
3
Example 11
def to_date(value):
"""
Function which knows how to convert timezone-aware :py:class:`~datetime.datetime` objects to
:py:class:`~datetime.date` objects, according to guidelines from `Django docuementation`_.
.. _Django docuementation: https://docs.djangoproject.com/en/dev/topics/i18n/timezones/#troubleshooting
"""
assert isinstance(value, (datetime.date, datetime.datetime))
if isinstance(value, datetime.date) and not isinstance(value, datetime.datetime):
return value
if timezone.is_aware(value) and timezone.pytz:
current_timezone = timezone.get_current_timezone()
return current_timezone.normalize(value.astimezone(current_timezone)).date()
else:
return value.date()
3
Example 12
def adapt_timefield_value(self, value):
if value is None:
return None
if isinstance(value, six.string_types):
return datetime.datetime.strptime(value, '%H:%M:%S')
# Oracle doesn't support tz-aware times
if timezone.is_aware(value):
raise ValueError("Oracle backend does not support timezone-aware times.")
return Oracle_datetime(1900, 1, 1, value.hour, value.minute,
value.second, value.microsecond)
3
Example 13
def default(self, o):
# See "Date Time String Format" in the ECMA-262 specification.
if isinstance(o, datetime.datetime):
return datetime_to_json_date(o)
elif isinstance(o, datetime.date):
return o.isoformat()
elif isinstance(o, datetime.time):
if is_aware(o):
raise ValueError("JSON can't represent timezone-aware times.")
r = o.isoformat()
if o.microsecond:
r = r[:12]
return r
elif isinstance(o, Decimal):
return str(o)
else:
return super(DateTimeJsonEncoder, self).default(o)
3
Example 14
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
3
Example 15
Project: GAE-Bulk-Mailer Source File: util.py
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
3
Example 16
def value_to_db_time(self, value):
"""
Transform a time value to an object compatible with what is expected
by the backend driver for time columns.
"""
if value is None:
return None
if timezone.is_aware(value):
raise ValueError("Django does not support timezone-aware times.")
return six.text_type(value)
3
Example 17
def value_to_db_datetime(self, value):
if value is None or isinstance(value, six.string_types):
return value
if timezone.is_aware(value):# and not self.connection.features.supports_timezones:
if getattr(settings, 'USE_TZ', False):
value = value.astimezone(timezone.utc).replace(tzinfo=None)
else:
raise ValueError("SQL Server backend does not support timezone-aware datetimes.")
return value.isoformat()
3
Example 18
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)
3
Example 19
def value_to_db_time(self, value):
if value is None:
return None
if isinstance(value, six.string_types):
return datetime.datetime.strptime(value, '%H:%M:%S')
# Oracle doesn't support tz-aware times
if timezone.is_aware(value):
raise ValueError("Oracle backend does not support timezone-aware times.")
return datetime.datetime(1900, 1, 1, value.hour, value.minute,
value.second, value.microsecond)
3
Example 20
Project: sentry Source File: sentry_helpers.py
@register.filter
def date(dt, arg=None):
from django.template.defaultfilters import date
if not timezone.is_aware(dt):
dt = dt.replace(tzinfo=timezone.utc)
return date(dt, arg)
3
Example 21
def test_make_naive(settings):
"""Tests datetimes can be made naive of timezones."""
settings.USE_TZ = True
datetime_object = datetime(2016, 1, 2, 21, 52, 25, tzinfo=pytz.utc)
assert timezone.is_aware(datetime_object)
naive_datetime = make_naive(datetime_object)
assert timezone.is_naive(naive_datetime)
3
Example 22
Project: pootle Source File: timezone.py
def test_make_naive_use_tz_false(settings):
"""Tests datetimes are left intact if `USE_TZ` is not in effect."""
settings.USE_TZ = False
datetime_object = datetime(2016, 1, 2, 21, 52, 25, tzinfo=pytz.utc)
assert timezone.is_aware(datetime_object)
naive_datetime = make_naive(datetime_object)
assert timezone.is_aware(naive_datetime)
3
Example 23
def value_to_db_datetime(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 = value.astimezone(timezone.utc).replace(tzinfo=None)
else:
raise ValueError("SQLite backend does not support timezone-aware datetimes when USE_TZ is False.")
return six.text_type(value)
3
Example 24
Project: PyClassLessons Source File: feedgenerator.py
def rfc3339_date(date):
# Support datetime objects older than 1900
date = datetime_safe.new_datetime(date)
time_str = date.strftime('%Y-%m-%dT%H:%M:%S')
if six.PY2: # strftime returns a byte string in Python 2
time_str = time_str.decode('utf-8')
if is_aware(date):
offset = date.tzinfo.utcoffset(date)
timezone = (offset.days * 24 * 60) + (offset.seconds // 60)
hour, minute = divmod(timezone, 60)
return time_str + '%+03d:%02d' % (hour, minute)
else:
return time_str + 'Z'
3
Example 25
Project: django-oauth2-provider Source File: models.py
def get_expire_delta(self, reference=None):
"""
Return the number of seconds until this token expires.
"""
if reference is None:
reference = now()
expiration = self.expires
if timezone:
if timezone.is_aware(reference) and timezone.is_naive(expiration):
# MySQL doesn't support timezone for datetime fields
# so we assume that the date was stored in the UTC timezone
expiration = timezone.make_aware(expiration, timezone.utc)
elif timezone.is_naive(reference) and timezone.is_aware(expiration):
reference = timezone.make_aware(reference, timezone.utc)
timedelta = expiration - reference
return timedelta.days*86400 + timedelta.seconds
3
Example 26
Project: django-celery Source File: utils.py
def correct_awareness(value):
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
3
Example 27
def adapt_timefield_value(self, value):
if value is None:
return None
# MySQL doesn't support tz-aware times
if timezone.is_aware(value):
raise ValueError("MySQL backend does not support timezone-aware times.")
return six.text_type(value)
3
Example 28
Project: django-twitter-api Source File: tests.py
def test_fetch_status(self):
self.assertEqual(Status.objects.count(), 0)
instance = Status.remote.fetch(STATUS_ID)
self.assertEqual(Status.objects.count(), 2)
self.assertEqual(instance.id, STATUS_ID)
self.assertEqual(instance.source, 'SocialEngage')
self.assertEqual(instance.source_url, 'http://www.exacttarget.com/social')
self.assertEqual(instance.text, '@mrshoranweyhey Thanks for the love! How about a follow for a follow? :) ^LF')
self.assertEqual(instance.in_reply_to_status_id, 327912852486762497)
self.assertEqual(instance.in_reply_to_user_id, 1323314442)
self.assertEqual(instance.in_reply_to_status, Status.objects.get(id=327912852486762497))
self.assertEqual(instance.in_reply_to_user, User.objects.get(id=1323314442))
self.assertIsInstance(instance.created_at, datetime)
self.assertTrue(is_aware(instance.created_at))
3
Example 29
def adapt_datetime_warn_on_aware_datetime(value):
# Remove this function and rely on the default adapter in Django 2.0.
if settings.USE_TZ and timezone.is_aware(value):
warnings.warn(
"The SQLite database adapter received an aware datetime (%s), "
"probably from cursor.execute(). Update your code to pass a "
"naive datetime in the database connection's time zone (UTC by "
"default).", RemovedInDjango20Warning)
# This doesn't account for the database connection's timezone,
# which isn't known. (That's why this adapter is deprecated.)
value = value.astimezone(timezone.utc).replace(tzinfo=None)
return value.isoformat(str(" "))
3
Example 30
def value_to_db_time(self, value):
"""
Transform a time value to an object compatible with what is expected
by the backend driver for time columns.
"""
if value is None:
return None
if is_aware(value):
raise ValueError("Django does not support timezone-aware times.")
return six.text_type(value)
3
Example 31
def adapt_timefield_value(self, value):
if value is None:
return None
# SQLite doesn't support tz-aware datetimes
if timezone.is_aware(value):
raise ValueError("SQLite backend does not support timezone-aware times.")
return six.text_type(value)
3
Example 32
def value_to_db_time(self, value):
"""
Transforms a time value to an object compatible with what is expected
by the backend driver for time columns.
"""
if value is None:
return None
if timezone.is_aware(value):
raise ValueError("Django does not support timezone-aware times.")
return six.text_type(value)
3
Example 33
def render(self, datestring):
"""Parses a date-like input string into a timezone aware Python
datetime.
"""
formats = ["%Y-%m-%dT%H:%M:%S.%f", "%Y-%m-%d %H:%M:%S.%f",
"%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S"]
if datestring:
for format in formats:
try:
parsed = datetime.strptime(datestring, format)
if not timezone.is_aware(parsed):
parsed = timezone.make_aware(parsed, timezone.utc)
return parsed
except Exception:
pass
return None
3
Example 34
def value_to_db_datetime(self, value):
if value is None:
return None
# Oracle doesn't support tz-aware datetimes
if timezone.is_aware(value):
if settings.USE_TZ:
value = value.astimezone(timezone.utc).replace(tzinfo=None)
else:
raise ValueError("Oracle backend does not support timezone-aware datetimes when USE_TZ is False.")
return six.text_type(value)
3
Example 35
def value_to_db_time(self, value):
if value is None:
return None
# MySQL doesn't support tz-aware times
if is_aware(value):
raise ValueError("MySQL backend does not support timezone-aware times.")
# MySQL doesn't support microseconds
return text_type(value.replace(microsecond=0))
3
Example 36
def value_to_db_time(self, value):
if value is None:
return None
# MySQL doesn't support tz-aware times
if timezone.is_aware(value):
raise ValueError("MySQL backend does not support timezone-aware times.")
return six.text_type(value)
3
Example 37
Project: decode-Django Source File: base.py
def value_to_db_datetime(self, value):
if value is None:
return None
不懂, 什么是 tz-aware
# MySQL doesn't support tz-aware datetimes 不支持 tz-aware 类型的时间
if timezone.is_aware(value):
if settings.USE_TZ:
value = value.astimezone(timezone.utc).replace(tzinfo=None)
else:
raise ValueError("MySQL backend does not support timezone-aware datetimes when USE_TZ is False.")
# MySQL doesn't support microseconds 不支持微秒
return six.text_type(value.replace(microsecond=0))
3
Example 38
Project: GAE-Bulk-Mailer Source File: feedgenerator.py
def rfc3339_date(date):
# Support datetime objects older than 1900
date = datetime_safe.new_datetime(date)
time_str = date.strftime('%Y-%m-%dT%H:%M:%S')
if not six.PY3: # strftime returns a byte string in Python 2
time_str = time_str.decode('utf-8')
if is_aware(date):
offset = date.tzinfo.utcoffset(date)
timezone = (offset.days * 24 * 60) + (offset.seconds // 60)
hour, minute = divmod(timezone, 60)
return time_str + '%+03d:%02d' % (hour, minute)
else:
return time_str + 'Z'
3
Example 39
def adapt_timefield_value(self, value):
if value is None:
return None
# Expression values are adapted by the database.
if hasattr(value, 'resolve_expression'):
return value
if isinstance(value, six.string_types):
return datetime.datetime.strptime(value, '%H:%M:%S')
# Oracle doesn't support tz-aware times
if timezone.is_aware(value):
raise ValueError("Oracle backend does not support timezone-aware times.")
return Oracle_datetime(1900, 1, 1, value.hour, value.minute,
value.second, value.microsecond)
3
Example 40
Project: django-jython Source File: operations.py
def value_to_db_time(self, value):
if value is None or isinstance(value, six.string_types):
return value
if timezone.is_aware(value):
if not getattr(settings, 'USE_TZ', False) and hasattr(value, 'astimezone'):
value = timezone.make_naive(value, timezone.utc)
else:
raise ValueError("SQL Server backend does not support timezone-aware times.")
return value.isoformat()
3
Example 41
def value_to_db_datetime(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 = value.astimezone(timezone.utc).replace(tzinfo=None)
else:
raise ValueError("MySQL backend does not support timezone-aware datetimes when USE_TZ is False.")
# MySQL doesn't support microseconds
return six.text_type(value.replace(microsecond=0))
3
Example 42
Project: cgstudiomap Source File: base.py
def adapt_datetime_warn_on_aware_datetime(value, conv):
# Remove this function and rely on the default adapter in Django 2.0.
if settings.USE_TZ and timezone.is_aware(value):
warnings.warn(
"The MySQL database adapter received an aware datetime (%s), "
"probably from cursor.execute(). Update your code to pass a "
"naive datetime in the database connection's time zone (UTC by "
"default).", RemovedInDjango20Warning)
# This doesn't account for the database connection's timezone,
# which isn't known. (That's why this adapter is deprecated.)
value = value.astimezone(timezone.utc).replace(tzinfo=None)
return Thing2Literal(value.strftime("%Y-%m-%d %H:%M:%S.%f"), conv)
3
Example 43
@models.permalink
def get_absolute_url(self):
"""
Builds and returns the entry's URL based on
the slug and the creation date.
"""
publication_date = self.publication_date
if timezone.is_aware(publication_date):
publication_date = timezone.localtime(publication_date)
return ('zinnia:entry_detail', (), {
'year': publication_date.strftime('%Y'),
'month': publication_date.strftime('%m'),
'day': publication_date.strftime('%d'),
'slug': self.slug})
3
Example 44
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
3
Example 45
def value_to_db_time(self, value):
if value is None:
return None
if isinstance(value, six.string_types):
return datetime.datetime.strptime(value, '%H:%M:%S')
# Oracle doesn't support tz-aware times
if timezone.is_aware(value):
raise ValueError("Oracle backend does not support timezone-aware times.")
return Oracle_datetime(1900, 1, 1, value.hour, value.minute,
value.second, value.microsecond)
3
Example 46
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
3
Example 47
def value_to_db_time(self, value):
if value is None:
return None
# MySQL doesn't support tz-aware times
if timezone.is_aware(value):
raise ValueError("MySQL backend does not support timezone-aware times.")
# MySQL doesn't support microseconds
return six.text_type(value.replace(microsecond=0))
3
Example 48
def value_to_db_time(self, value):
if value is None:
return None
# SQLite doesn't support tz-aware datetimes
if timezone.is_aware(value):
raise ValueError("SQLite backend does not support timezone-aware times.")
return six.text_type(value)
3
Example 49
Project: pythondotorg Source File: utils.py
def convert_dt_to_aware(dt):
if not isinstance(dt, datetime.datetime):
dt = date_to_datetime(dt)
if not is_aware(dt):
# we don't want to use get_current_timezone() because
# settings.TIME_ZONE may be set something different than
# UTC in the future
return make_aware(dt, timezone=pytz.UTC)
return dt
3
Example 50
Project: cgstudiomap Source File: operations.py
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)